user2242294
user2242294

Reputation:

Apache .htaccess file not rewriting properly

I have an .htaccess file. It needs to rewrite URLs in two cases: for the MVC framework and in a more special case. I want to rewrite any requests to "/resources/newspaper" if the user doesn't have a cookie named "cfnw-hash". I've tried putting the code before the MVC code and after it. Doesn't work. It worked before switching over to the MVC framework, though I really don't have enough .htaccess knowledge to see if that's causing the issue. Here's code:

Options -Indexes

<IfModule mod_rewrite.c>
    Options -Indexes

    RewriteEngine On
    RewriteBase /

    # Force to exclude the trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.*)/$
    RewriteRule ^(.+)/$ $1 [R=307,L]

    # Allow any files or directories that exist to be displayed directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule ^(.*)$ index.php?$1 [QSA,L]
</IfModule>

RewriteEngine On
RewriteCond %{HTTP_COOKIE} !cfnw-hash [NC]
RewriteRule \/resources\/newspaper.* http://www.example.com/error/401 [R=401,NC,L]

Upvotes: 2

Views: 80

Answers (2)

Panama Jack
Panama Jack

Reputation: 24448

Combine your rules and I think you RewriteRule might not be matching because of the prepending / and also the cookie matching. Try this. Notice the cookie part that you update with your cookie.

Options -Indexes

<IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteBase /

    RewriteCond %{HTTP_COOKIE}  !cookie_name=specific_value; [NC]
    RewriteRule ^resources/newspaper/?(.*) http://www.example.com/error/401 [R=401,NC,L]

    # Force to exclude the trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.*)/$
    RewriteRule ^(.+)/$ $1 [R=307,L]

    # Allow any files or directories that exist to be displayed directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule ^(.*)$ index.php?$1 [QSA,L]
</IfModule>

Upvotes: 1

anubhava
anubhava

Reputation: 785058

Have it this way:

<IfModule mod_rewrite.c>
    Options -Indexes

    RewriteEngine On
    RewriteBase /

    RewriteCond %{HTTP_COOKIE} !cfnw-hash [NC]
    RewriteRule ^resources/newspaper /error/401 [R=401,NC,L]    

    # Force to exclude the trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.*)/$
    RewriteRule ^(.+)/$ $1 [R=307,L]

    # Allow any files or directories that exist to be displayed directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d    
    RewriteRule ^(.*)$ index.php?$1 [QSA,L]
</IfModule>

Test this after clearing your browser cache.

Upvotes: 0

Related Questions