关于如何创建无扩展名URL以及如何将索引重定向到root,有很多答案。我在htaccess文件中很难将两者结合起来。一个人总是与另一个人产生问题。以下是我想要完成的事情:
301重定向
domain.com to www.domain.com
domain.com/index.php to www.domain.com
domain.com/index to www.domain.com
www.domain.com/index.php to www.domain.com
www.domain.com/index to www.domain.com
/all-other-pages.php to /all-other-pages
/all-other-pages/ to /all-other-pages (if not a directory)
目前我正在使用它:
#-------------------------------------------------------------------------------
# REWRITE TO NON-EXTENSION URL
# 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]
#-------------------------------------------------------------------------------
# REDIRECT TO WWW LOCATION
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^.*/index$
RewriteRule ^(.*)index$ /$1 [R=301,L]
#RewriteCond %{HTTP_HOST} !^$
#RewriteCond %{HTTP_HOST} !^www\. [NC]
#RewriteCond %{HTTPS}s ^on(s)|
#RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
在我尝试之前一切顺利: www.example.com/index.php
重定向到:
www.example.com/index
我没有跟踪我尝试过的所有变化,抱歉。 这段代码是复制和粘贴的,我通常不喜欢在我不理解代码的情况下做,但我担心我真的无法学习htaccess和regex的复杂性此刻。
document_root中只有一个htaccess文件,但是,我将有一个子目录,我想要发生相同类型的页面重定向。
感谢您的帮助, 百里
答案 0 :(得分:0)
按此顺序制定规则:
RewriteEngine On
# REDIRECT TO WWW LOCATION
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# remove index.php
RewriteCond %{THE_REQUEST} /index(\.php)?[/?\s] [NC]
RewriteRule ^(.*?)index(?:\.php)?$ /$1 [L,R=301,NC,NE]
# redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} \.php[/?\s] [NC]
RewriteRule ^(.+)\.php $1 [R=301,L]
# 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]
确保在清除浏览器缓存后对其进行测试。