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.

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

报告相同问题?