douweiluo0600 2014-01-11 23:04 采纳率: 0%
浏览 133
已采纳

mod_rewrite httpd.conf:阻止访问HTTP_REFERER上的目录

I am (learning) implementing a Front Controller pattern, redirecting all requests to index.php and appending as a query string (to be parsed later by PHP) via a mod_rewrite rule in httpd.conf, below:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php/$1 [NC,L]

Problem 1: This is also redirecting needed existing files, such as domain.com/css/main.css. Shouldn't !-d and !-f be preventing this?

Problem 2: I want to block access (403) to certain directories and their contents -- domain.com/css/*, domain.com/js/*, etc -- unless the request comes from domain.com.

Exposition

I have the following rule to block requests based on HTTP_REFERER (from a blog, can't find the link...), which by itself blocks all user requests:

RewriteCond %{HTTP_HOST}@@%{HTTP_REFERER} !^([^@]*)@@https?://\1/.*
RewriteRule ^.*$ - [F]

I want to add another condition, checking if REQUEST_URI is for anything in those directories, but am having trouble getting it to work. If I add the below:

RewriteCond %{REQUEST_URI} /?.*(css|js)/?.* [NC]

Then everything is redirected; without it, everything is blocked. So, the full mod_rewrite set is as below:

RewriteCond %{REQUEST_URI} /?.*(css|js)/?.* [NC]
RewriteCond %{HTTP_HOST}@@%{HTTP_REFERER} !^([^@]*)@@https?://\1/.*
RewriteRule ^.*$ - [F]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php/$1 [NC,L]

Any assistance will be greatly appreciated; I've been searching for an answer all day.

  • 写回答

1条回答 默认 最新

  • douxi7219 2014-01-11 23:31
    关注

    Problem 1: This is also redirecting needed existing files, such as domain.com/css/main.css. Shouldn't !-d and !-f be preventing this?

    It's supposed to, but it's possible that mod_rewrite doesn't have the right context. Rewrite rules in server config behave a little differently than in, say, an htaccess file. Try placing the rules in a <Directory> container:

    <Directory "/path/to/your/docuemntroot">
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ /index.php/$1 [NC,L]
    
    </Directory>
    

    For Problem 2, you can simply add the regex to the rule itself:

    RewriteCond %{HTTP_HOST}@@%{HTTP_REFERER} !^([^@]*)@@https?://\1/.*
    RewriteRule \.(css|js)$ - [F,L,NC]
    

    And make sure you use the L flag to prevent the second rule from getting applied.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误
  • ¥15 openpcdet自制数据集评估bev精度和3d精度相同
  • ¥15 excel 上下按钮 显示行
  • ¥20 云卓h12pro 数传问题