【问题标题】:wildcard .htaccess and reject some address on subdomain通配符 .htaccess 并拒绝子域上的某些地址
【发布时间】:2014-10-18 01:17:52
【问题描述】:

我希望 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.phpindex.php 存在于根目录中)

为什么?我该如何解决?

【问题讨论】:

  • 第一组规则不行。它结合了前两个 RewriteCond (默认)和 OR 到第三个之间的 AND。您还必须添加排除 index.php。

标签: regex apache .htaccess mod-rewrite redirect


【解决方案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]

【讨论】:

  • 确定当目录存在但主机不是以up.开头时不会触发第一条规则? condition1 AND condition2 OR condition3 即使只满足 condition3 也可以工作。
  • 感谢这个解决方案,现在我还有其他问题,那就是http://up.example.com/index.php url open。
  • ok,在浏览器中输入http://up.example.com/index.php是什么问题?
  • @anubhava,非常感谢,现在开始工作了!在此之前,我在这个问题上工作了大约 1 周 :-D
【解决方案2】:

试试这个

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]

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 2016-10-18
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 2014-09-06
    • 2012-01-23
    • 1970-01-01
    • 2017-11-02
    相关资源
    最近更新 更多