douweiluo0600 2014-01-11 23:04
浏览 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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!