问题描述
我想使用 .htaccess
修改我服务器上的 URL,但我遇到了一些问题。
在我的 previous question 中,我描述了我想要的所有修改。我想在 previous rules 旁边添加一些新规则。
RewriteEngine On
# matches /site/ or /site/index.PHP or
# /a/site/index.PHP or /b/site/index.PHP
# captures a/ or b/ or an empty string in %1
# redirects to /a/ or /b/ or /
RewriteCond %{THE_REQUEST} \s/+([ab]/|)site/(?:index\.PHP)?[?\s] [NC]
RewriteRule ^ /%1 [L,R=302,NE]
# matches a/ or b/ or empty (landing page)
# rewrites to a/site/index.PHP or b/site/index.PHP or site/index.PHP
RewriteRule ^([ab]/)?$ $1site/index.PHP [L,NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.PHP -f
RewriteRule ^(.+?)/?$ $1.PHP [L]
新规则 #1:
https://example.com/site/index.PHP
(已经)
https://example.com/site/index
(不会)
https://example.com/site/
(已经)
应该转换为短网址。
https://example.com/
新规则 #2:
https://example.com/a/site/index.PHP
(已经)
https://example.com/a/site/index
(不会)
https://example.com/a/site/
(已经)
应该转换为短网址。
https://example.com/a/
新规则 #3:
https://example.com/site/any.PHP
(不会)
https://example.com/site/any
(不会)
应该转换为短网址。
https://example.com/any/
新规则 #4:
https://example.com/any/
(不会)
应加载完整网址而不展开。
https://example.com/site/any.PHP
注意: any.PHP
是动态的,意味着它是 ([\w]+).PHP
,我不知道写 .htaccess
,任何帮助将不胜感激.
解决方法
您可以在站点根目录 .htaccess 中尝试这些规则:
RewriteEngine On
# matches /site/ or /site/index.php or
# /a/site/index.php or /b/site/index.php
# captures a/ or b/ or an empty string in %1
# redirects to /a/ or /b/ or /
RewriteCond %{THE_REQUEST} \s/+([ab]/|)site/(?:index(?:\.php)?)?[?\s] [NC]
RewriteRule ^ /%1 [L,R=302,NE]
# removes site/ from URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{THE_REQUEST} \s/+site/(\S+?)(?:\.php)?/?\s [NC]
RewriteRule ^ /%1/ [L,NE]
# remove .php from all URLs
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1/ [R=302,NE,L]
# add trailing slash to all URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,NE]
# matches a/ or b/ or empty (landing page)
# rewrites to a/site/index.php or b/site/index.php or site/index.php
RewriteRule ^([ab]/)?$ $1site/index.php [L,NC]
# adds .php internally to /any
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]
# adds .php internally to /site/any
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/site/$1.php -f
RewriteRule ^(.+?)/?$ site/$1.php [L]
每条规则前都有注释以阐明其作用。