我想让我的所有网址统一干净。这意味着我的所有网址都没有扩展名,也没有斜杠,如果有人输入.php
或尾随斜杠,则只会将此人重定向到干净的网址。
示例:
example.com/blog/file.php
和
example.com/blog/file/
会重定向到
example.com/blog/file
答案 0 :(得分:5)
在.htaccess
试试这个:
RewriteEngine on
#unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]
#resolve .php file for extensionless php urls
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
#redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(([^/]+/)*[^.]+)\.php /$1 [R=301,L]
答案 1 :(得分:3)
我的网络主机最近(2011年9月)将他们的Apache服务器更新为更新版本的Apache,而我的旧.htaccess
代码显示无扩展名的URL不再有效。在大量复制代码(可能适用于旧版本的Apache OS)和测试失败之后,我能够确定以下代码似乎在我的服务器和其他几个代码上运行:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(([^/]+/)*[^.]+)\.php http://www.example.com/$1 [R=301,L]
尝试一下 - -Multiviews
似乎是让它发挥作用的关键因素。
答案 2 :(得分:0)
如果您的网站托管在启用了Apache Mod-Rewrite模块的Linux服务器上,则可以使用.htaccess重定向文件。此链接with information on how to format the file for your purpose 可能会有所帮助。
答案 3 :(得分:0)
# Turn off the need of directory slash redirecting
DirectorySlash Off
# Turn on RewriteEngine
RewriteEngine On
# Internally redirect request to php file
RewriteCond "%{REQUEST_FILENAME}" !-f
RewriteCond "%{REQUEST_FILENAME}\.php" -f
RewriteRule "(.*)" "$1.php" [L]
# External redirects
# The above line is used to determine whether a internal redirect is done or not.
# If it is internally redirected, REDIRECT_STATUS will become 200.
# RewriteCond "%{ENV:REDIRECT_STATUS}" "^$"
# Redirect request with .php extension to extensionless
RewriteCond "%{ENV:REDIRECT_STATUS}" "^$"
RewriteRule "(.*)\.php$" "$1" [R=301]
# Redirect request with trailing slash to slashless
RewriteCond "%{ENV:REDIRECT_STATUS}" "^$"
RewriteCond "%{REQUSET_FILENAME} -d
RewriteCond "%{REQUSET_FILENAME} !-f
RewriteRule "(.*)\/" "$1" [R=301]