Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write multiple conditions and rules for .htaccess?

I have the following in an .htaccess file for my website

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteRule ^(.*)$ profile.php?membername=$1 [L]
    RewriteRule ^poem/(.*)/?$ poem.php?id=$1 [L,NC]
</IfModule>


# Works
RewriteRule ^(.*)$ profile.php?membername=$1 [L]
# Does not work
RewriteRule ^poem/(.*)/?$ poem.php?id=$1 [L,NC]

If change it all to this bellow then the outcome is reversed.

# No longer works:
RewriteRule ^(.*)$ profile.php?membername=$1 [L]
# Now works:
RewriteRule ^poem/(.*)/?$ poem.php?id=$1 [L,NC]


<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{SCRIPT_FILENAME} -f
    RewriteCond %{SCRIPT_FILENAME} -d
    RewriteRule ^(.*)$ profile.php?membername=$1 [L]
    RewriteRule ^poem/(.*)/?$ poem.php?id=$1 [L,NC]
</IfModule>

What's going on? I have no idea.

like image 213
Joshua Avatar asked Jan 27 '26 11:01

Joshua


1 Answers

Looks like what you need to do here is to keep the negative tests on REQUEST_FILENAME and reverse the order of the rules. Otherwise, the more generic ^(.*) always matches first, and overrules ^poem/.

<IfModule mod_rewrite.c>
    RewriteEngine On
    # Negative conditions here...
    # Using REQUEST_FILENAME instead of SCRIPT_FILENAME
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # Match the more specific rule first...
    RewriteRule ^poem/(.*)/?$ poem.php?id=$1 [L,NC]

    # Match the generic rule last.
    RewriteRule ^(.*)$ profile.php?membername=$1 [L]
</IfModule>
like image 149
Michael Berkowski Avatar answered Jan 30 '26 01:01

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!