.htaccess URL使用mod_rewrite重写文件扩展名和前端控制器

时间:2017-05-06 15:24:17

标签: .htaccess mod-rewrite url-rewriting

我目前有一个文件正在从网址中删除.php,以使其整洁,并且更适合搜索引擎优化。

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]

我写错了这行并导致它循环吗?

1 个答案:

答案 0 :(得分:1)

RewriteRule ^(.*)$ Main.php?Page=$1.php [QSA,L]

在重写网址之前,您需要确保自己不在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追加到LoginindexSignup,而不是任何存在的文件。 其他所有(包括不存在的文件)会被重写为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]