我希望up.example.com
子域名下的所有文件或目录都被拒绝,并显示404错误。
此外,我希望所有其他请求指向index.php
。
我写这段代码:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^up\.(.+)$ [NC]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ - [R=404,L,NS]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L,QSA]
当我为http://up.example.com/test.jpg
如果根服务器上存在test.jpg
文件,请显示以下错误:
Not Found
The requested URL /test.jpg was not found on this server.
Apache Server at up.example.com Port 80
没关系!
但是当test.jpg
不存在时,请给我这个错误:
Not Found
The requested URL /index.php was not found on this server.
Apache Server at up.example.com Port 80
而是打开index.php
(index.php
存在于root上)
为什么呢?我该如何解决?
答案 0 :(得分:1)
试试这个
RewriteEngine On
RewriteCond %{HTTP_HOST} ^up\.(.+)$ [NC] # remove if it is not related to subdomain
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L,QSA]
RewriteCond %{HTTP_HOST} ^up\.(.+)$ [NC]
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteRule ^(.*)$ - [R=404,L,NS]
答案 1 :(得分:1)
实际上问题是您将所有内容写入index.php
并且该请求成为有效文件。当mod_rewrite
下次运行时,第一个规则会将其发送到404。
要克服此错误,请遵守以下规则:
RewriteEngine On
# if it is valid file or directory except for index.php
# then send 404 to browser
RewriteCond %{HTTP_HOST} ^up\. [NC]
RewriteCond %{THE_REQUEST} \s/+index\.php[?\s] [NC]
RewriteRule ^index\.php$ - [R=404,L,NC]
RewriteCond %{HTTP_HOST} ^up\. [NC]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule !^index\.php$ - [R=404,L,NC]
# send all non-file/directories to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]