404重定向有效,但会将浏览器中重写的URL路径更改为完整的URL路径

时间:2013-07-10 13:55:52

标签: .htaccess url url-rewriting http-status-code-404

我使用以下URL重写方案:

example.com/about/
example.com/this/is/a/page/

前往:

example.com/pages/about/about.php
example.com/pages/this/is/a/page/page.php

一切正常,但在404错误时,在example.com/badpage/中输入时会显示404页面,但会将网址字符串更改为example.com/pages/badpage/badpage.php

如果在404错误中保持URL相同怎么办?

(htaccess还在请求的URL末尾加上'/',您可以从下面的代码中看到)


htaccesss代码:

DirectoryIndex /pages/index/index.php
ErrorDocument 404 /pages/error/404.php

RewriteEngine On

#Removes the www from domain for SEO
RewriteCond %{HTTP_HOST} ^www\.portal\.example\.com$ [NC]
RewriteRule ^(.*)$ http://portal.example.com/$1 [L,R=301]

# Don't fix direct file links
RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://portal.example.com/$1/ [L,R=301]

RewriteRule     ^([A-Za-z0-9_-]+)/?$    pages/$1/$1.php    [NC,L]
RewriteRule     ^([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$    pages/$1/$2/$2.php    [NC,L]
RewriteRule     ^([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$    pages/$1/$2/$3/$3.php    [NC,L]
RewriteRule     ^([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$    pages/$1/$2/$3/$4/$4.php    [NC,L]

1 个答案:

答案 0 :(得分:0)

您需要在每次重写之前添加条件,以确保您不会盲目地重写为不存在的文件。主要是,最后的4条规则需要有一些条件:

RewriteCond %{REQUEST_URI} ^/([A-Za-z0-9_-]+)/?$
RewriteCond %{DOCUMENT_ROOT}/pages/%1/%1.php -f
RewriteRule ^ pages/%1/%1.php [NC,L]

第一个条件创建一个使用%1反向引用的分组。第二个条件创建一个您尝试重写的路径,并使用-f检查该文件是否存在。其他人也一样:

RewriteCond %{REQUEST_URI} ^/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$
RewriteCond %{DOCUMENT_ROOT}/pages/%1/%2/%2.php -f
RewriteRule ^ pages/%1/%2/%2.php [NC,L]

RewriteCond %{REQUEST_URI} ^/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$
RewriteCond %{DOCUMENT_ROOT}/pages/%1/%2/%3/%3.php -f
RewriteRule ^ pages/%1/%2/%3/%3.php [NC,L]

RewriteCond %{REQUEST_URI} ^/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/([A-Za-z0-9_-]+)/?$
RewriteCond %{DOCUMENT_ROOT}/pages/%1/%2/%3/%4/%4.php -f
RewriteRule ^ pages/%1/%2/%3/%4/%4.php [NC,L]