0

我使用以下 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 页面,但会将 URL 字符串更改为example.com/pages/badpage/badpage.php.

即使出现 404 错误,如何保持 URL 不变?

(从下面的代码中可以看到,htaccess 还在请求的 URL 的末尾添加了“/”)


htaccess 代码:

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]
4

1 回答 1

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]
于 2013-07-10T22:06:08.250 回答