apache URL 重写 - 无文件扩展名的重定向

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/681322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 17:25:10  来源:igfitidea点击:

URL Rewriting - Redirect With No File Extension

apache.htaccessfriendly-urlurl-rewriting

提问by Cory Dee

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

我目前在 .htaccess 文件中使用以下规则:

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

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

这可以很好地确保/myfile.php正常工作myfile(在 URL 中没有扩展名)。它还可以毫无问题地处理查询字符串,因此myfile?var=foo也可以使用。

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

问题是这些在 Google Analytics 中注册为两个单独的文件。因此,虽然myfile.php可能是我网站上第三大最受欢迎的页面,有 X 次访问,但myfile可能是我网站上第五大最受欢迎的页面,有 Y 次访问。

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

如何进行硬重定向,而不是“接受任一”类型的规则?

回答by Gumbo

Try this rule to redirect requests for .phpfiles:

试试这个规则来重定向.php文件请求:

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

回答by Eric Petroelje

Could you just change your last RewriteRule to do this?

你能不能改变你的最后一个 RewriteRule 来做到这一点?

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

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

这会将“myfile”重定向到“myfile.php”。

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

此外,您也可以使用规则在 Google Analytics 内部对此进行调整。虽然这可能不是一个理想的解决方案。

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

ETA:如果您希望 myfile.php 重定向到 myfile,请尝试将其作为最后一条规则:

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

回答by Kzar

You could just put in your pages a

你可以把你的页面

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

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

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

回答by roadsunknown

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 ^(.*)$ .php

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

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

在这里找到:http: //www.webmasterworld.com/apache/3961636.htm