Apache mod_rewrite重定向到PHP,而是重定向到其他URL


Apache mod_rewrite not redirecting to PHP, but redirecting to other URLs

我的.htaccess文件中有一个代码。它将每个.php重定向到非 php。我希望它只定向一个 php 文件,而不重定向其余文件。例如,我希望 ABC.php 是 ABC,但 BCD.php 保持为 BCD.php.。如何修改此脚本以获得此结果?谢谢。

RewriteEngine on
#Redirect non-php to php and stop futher processing
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}'.php -f
RewriteRule ^(.*)$ $1.php [L]
#redirect .php to non-php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)'.php$ $1 [R=301,L]

这段代码应该适合你:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}'s/+(abc)'.php[?'s] [NC]
RewriteRule ^ %1 [R=301,L]
#Redirect non-php to php and stop futher processing
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}'.php -f
RewriteRule ^(.*)$ $1.php [L]

重要的是在这里使用%{THE_REQUEST},它表示Apache收到的原始HTTP请求,以避免循环。 %{THE_REQUEST}不会使用各种重写规则进行重写,而不是使用用于RewriteRule的 URI 模式的情况。

将带有 exception 的规则和 L 标志放在一般的 RewriteRule 之前:

RewriteEngine on
#redirect abc.php to abc
RewriteRule ^abc'.php$ abc [R=301,L]
#Redirect non-php to php and stop futher processing
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}'.php -f
RewriteCond %{REQUEST_URI} ! abc$
RewriteRule ^(.*)$ $1.php [L]