Search code examples
.htaccessmod-rewriteskip

.htaccess mod_rewrite won't skip RewriteRule with [S]


As an FYI, I am using the following .htaccess file in located at www.site.com/content/

When a user visits www.site.com/content/login I want it to display the content from www.site.com/content/userlogin.php (masked via rewrite, and not redirect) - which I have done SUCCESSFULLY like so:

RewriteEngine On
RewriteBase /content/
RewriteRule ^login/?$ /content/userlogin.php [NC,L]


However, I would like to add the follwoing: If they try to access www.site.com/content/userlogin.php directly, I want them to get redirected to a 404 page at www.site.com/content/error/404.php

RewriteEngine On
RewriteBase /content/
RewriteRule ^login/?$ /content/userlogin.php [NC,S=1,L]
RewriteRule ^userlogin\.php$ /content/error/404.php [NC,L]


With that in the .htaccess file, both www.site.com/content/login and www.site.com/content/userlogin.php show www.site.com/content/error/404.php


Solution

  • First the S=1 will have no function as the L directive will make any further rewriting stop. It seems like the first RewriteRule makes Apache go through the .htaccess rules one more time, so you need to know if the first rewrite has happend. You could do this by setting an environment variable like this:

    RewriteRule ^login/?$ /content/userlogin.php [E=DONE:true,NC,L]
    

    So when the next redirect occurs the Environment variable actually gets rewritten to REDIRECT_<variable> and you can do a RewriteCond on this one like this:

    RewriteCond %{ENV:REDIRECT_DONE} !true
    RewriteRule ^userlogin\.php$ /content/error/404.php [NC,L]
    

    Hope this helps