我目前有一个文件正在从URL中删除.php
,以使其整洁,更适合SEO。
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]
我有一个名为Main.php
的页面,我使用Main.php?Page=page1.php
显示其他页面。我想向我的.htaccess
文件添加一个规则,该规则仍允许我删除.php
规则并使Main.php?Page=page1.php
显示为
URL.com/page1
这可能吗?当我将以下行添加到我的文件中时,我的主页开始循环加载,当我删除该行时,它工作正常。
RewriteRule ^(.*)$ Main.php?Page=$1.php [QSA,L]
我是否写错了这一行并导致它循环?
RewriteRule ^(.*)$ Main.php?Page=$1.php [QSA,L]
在重写 URL 之前,您需要确保尚未Main.php
。这就是导致循环的电流...Main.php?Page=Main.php.php&Page=Main....
等
尝试类似操作:
# (1) If requesting a ".php" file (including "Main.php")
# or any known static resource then stop here...
RewriteRule .(php|css|js|jpe?g|png|gif)$ - [L]
# (3) Otherwise, if the request doesn't map to an existing file then rewrite to Main.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) Main.php?Page=$1.php [QSA,L]
如果不在原始请求上传递查询字符串,请删除QSA
标志。
RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^.]+)$ $1.php [NC,L]
您之前附加.php
扩展的指令应该检查附加.php
是否会导致有效的请求,否则这将.php
附加到所有非 php 请求并且永远不会达到Main.php
。像这样:
# (2) Append ".php" if there is no extension
# but only if appending ".php" would result in a valid request
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^.]+)$ $1.php [L]
无需在字符类中转义点。这里不需要NC
标志。
这些因素结合在一起,我们有:
# (1) If requesting a ".php" file (including "Main.php")
# or any known static resource then stop here...
RewriteRule .(php|css|js|jpe?g|png|gif)$ - [L]
# (2) Append ".php" if there is no extension
# but only if appending ".php" would result in a valid request
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^.]+)$ $1.php [L]
# (3) Otherwise, if the request doesn't map to an existing file then rewrite to Main.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) Main.php?Page=$1.php [QSA,L]
更新#2:仅将.php
附加到Login
,index
和Signup
,而不是任何存在的文件。其他所有内容(包括不存在的文件)都将重写为Main.php
.
# (2) Append ".php" to select requests
# but only if appending ".php" would result in a valid request
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(Login|index|Signup)$ $1.php [L]
# (3) Otherwise, rewrite everything else to Main.php
RewriteRule (.*) Main.php?Page=$1.php [QSA,L]