mod_rewrite : if / else type RewriteRule

The following rewrite passes a string starting with the number 4 as a variable to process.php :

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(4[^/]*)$ /process.php?variable=$1 [L]

So this

Read More
http://www.domain.com/4shopping

is mapped to

http://www.domain.com/process.php?variable=4shopping

But I want to extend this last rewrite rule to basically state:

if word begins with 4, map to /process.php?variable=$1
else map to /index.php

The second (else) part of this statement is the basic WordPress rewrite rule. So for example:

http://www.domain.com/shopping

which has no 4 will be directed to

http://www.domain.com/index.php?shopping (I believe this is how WordPress permalinks work!)

Related posts

Leave a Reply

3 comments

  1. Try this:

    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    
    RewriteRule ^(4[^/]*)$ process.php?variable=$1 [L]
    RewriteRule ^([^4/][^/]*)$ index.php?$1 [L]
    

    The first rule will catch any request that can be mapped to an existing file or directory and will end the rewrite process. The second rule is yours (without the RewriteCond conditions). And the third rule will catch any request that’s URL path does not start with the number 4.

  2. Here’s the solution:

    RewriteRule ^(4[^/]*)$ /feedback.php?sms_code=$1 [L]
    #
    # BEGIN wordpress
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    # END wordpress
    

    I left the default WordPress rules in place, and added my own conditional rule above, making sure to terminate [L] processing if the condition was met

  3. I would add two lines to the end of what you already have. The additional rules will convert to index.php anything that hasn’t already been converted to process.php.

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(4[^/]*)$ /process.php?variable=$1 [L]
    
    RewriteCond %{SCRIPT_FILENAME} !process.php
    RewriteRule ^([^/]*)$ index.php?$1