修改 URL 为 .htaccess [#Q2.]

Modify URL with .htaccess [#Q2.]

我想使用 .htaccess 修改服务器上的 URL,但我遇到了一些问题。

在我的 I described all the modifications I wanted. I want add some new rules along side the .

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]/)?$ site/index.php [L,NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule ^(.+?)/?$ .php [L]

新规则#1:

https://example.com/site/index.php (already does)

https://example.com/site/index (does not)

https://example.com/site/ (already does)

should get converted to short url.

https://example.com/

新规则#2:

https://example.com/a/site/index.php (already does)

https://example.com/a/site/index (does not)

https://example.com/a/site/ (already does)

should get converted to short url.

https://example.com/a/

新规则#3:

https://example.com/site/any.php (does not)

https://example.com/site/any (does not)

should get converted to short url.

https://example.com/any/

新规则#4:

https://example.com/any/ (does not)

should load full url without expanding.

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,R=302,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,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]/)?$ site/index.php [L,NC]

# adds .php internally to /any
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule ^(.+?)/?$ .php [L]

# adds .php internally to /site/any
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/site/.php -f
RewriteRule ^(.+?)/?$ site/.php [L]

每条规则前都有注释来阐明它的作用。