URL Rewriting - Redirect With No File Extension

情到浓时终转凉″ 提交于 2021-02-07 19:45:57

问题


I am currently using the following rules in a .htaccess file:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

This works well to ensure that /myfile.php works as well as just myfile (with no extension in the URL). It also handles querystrings with no problems, so myfile?var=foo also works.

The problem is that these are registering in Google Analytics as being two separate files. So while myfile.php might be the third most popular page on my site, with X visits, myfile might be the fifth most popular page on my site with Y visits.

How can I do a hard redirect, rather than "accept either one" type of rule?


回答1:


Try this rule to redirect requests for .php files:

RewriteCond %{THE_REQUEST} ^GET\ /(([^/?]*/)*[^/?]+)\.php
RewriteRule ^.+\.php$ /%1 [L,R=301]



回答2:


Could you just change your last RewriteRule to do this?

RewriteRule ^(.*)$ $1.php [L,R=301]

That will redirect "myfile" to "myfile.php".

Also, you can adjust for this inside of Google Analytics using rules as well. Although that probably isn't an ideal solution.

ETA: If you want myfile.php to redirect to myfile, try this for your last rule instead:

RewriteRule ^(.+)\.php$ $1 [L,R=301]



回答3:


You could just put in your pages a

<link rel="canonical" href="..." />

https://support.google.com/webmasters/answer/139066?hl=en




回答4:


Took me a few hours...but I believe I have finally found the answer.

// The Original
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

// Add This
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(([^/]+/)*[^.]+)\.php /$1 [R=301,L]

Found here: http://www.webmasterworld.com/apache/3961636.htm



来源:https://stackoverflow.com/questions/681322/url-rewriting-redirect-with-no-file-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!