Search code examples
phpapache.htaccessmod-rewrite

htaccess rewrite some urls but send all others to another page


This is my .htaccess file:

RewriteEngine On
DirectoryIndex index.php

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^login      login_reg.php [L] [NC]
RewriteRule ^(.+)       redirect.php?shortcode=$1 [L] [NC]

What I want is for anything other than '/login' and root '/' to be redirected to redirect.php with the request_url (the bit after the slash) being substituted as the shortcode GET variable.

However, the file above gives me an error: "The page isn’t redirecting properly"


Solution

  • Few issues:

    1. Pattern of login will also match rewritten login_reg.php
    2. RewriteCond will be applicable to immediate next RewriteRule only hence last rule is rewriting everything infinitely.
    3. Flags need to be in a single [...]

    You can use these rules in your .htaccess:

    DirectoryIndex index.php
    RewriteEngine On
    
    RewriteRule ^login/?$ login_reg.php [L,NC]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule (.+) redirect.php?shortcode=$1 [L,NC,QSA]