htaccess重写,如何否定子目录文件

时间:2014-02-11 01:37:33

标签: .htaccess mod-rewrite url-rewriting

我有htaccess文件执行URL重写。它基本上删除了.php扩展名。

规则运作良好,例如他们成功将http://example.com/contact.php重写为http://example.com/contact

但是,重写也会更改子目录文件,例如/includes/check-form-input.php

因此,例如,当contact.php处的表单尝试提交到/includes/check-form-input.php时,htaccess重写将从末尾删除.php并获得404标题。
即找不到/includes/check-form-input

至少看起来似乎发生了什么,使用HTTP_REFERER似乎证实了这一点,因为引用者/includes/check-form-input没有ext .php

有没有办法添加规则来否定所有子目录?

我有以下htaccess - 这是从SO的另一个答案复制而来的,因为我没有100%掌握重写结构。
(如果是原因,我已经离开了www到非www重定向)

## Rewrite on
RewriteEngine on


## Redirect all pages from non-www to www
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]


## URL rewrite
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/$1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/$1 [R=301,L]

# Resolve .php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]

1 个答案:

答案 0 :(得分:1)

您可以排除所有子目录,

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^([^/]+)\.php$ http://example.com/$1 [R=301,L]

或将其限制为仅限GET请求:

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(GET|HEAD)\ (.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/$1 [R=301,L]

或只是排除includes子目录

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteCond %{REQUEST_URI} !^/includes/
RewriteRule ^([^/]+)\.php$ http://example.com/$1 [R=301,L]