Multiple htaccess rewrite rule

here is my code for the .htaccess file

Options -Indexes RewriteEngine On RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule ^([a-z0-9]+)$ /profile.php?username=$1 [L] RewriteRule ^([a-z0-9]+)$ /display.php?page=$1 [L] 

For the first, it works correctly and is displayed as follows: www.site.com/user

The second does not work, it is usually displayed like this: www.site.com/display.php?page=10. I want to display the page as follows: www.site.com/article I tried different things and no result. Please tell me how to do it in order to work with several rules. Also, please give me advice on how to use these functions in php, because I think I did something not very good. My PHP code to use this rule:

 <p><a class="button" href="/<?php echo $user_data['username']; ?>"> Profile</a></p> 

This works, but perhaps this is the best way to make a link to use htaccess.

+6
source share
3 answers

The two rules that conflict with you, the patterns used are exactly the same, which means that in addition to the conditions that apply only to the first rule, these two rules are completely indistinguishable.

Given this url:

 http://www.site.com/blah 

Is the " blah " page or user? I can’t say, because the regular expression pattern ( ^([a-z0-9]+)$ ) for both rules corresponds to "blah". So, the first will always apply no matter what. You need to add something to distinguish 2, for example, including a "user" or a "page" in the url:

 http://www.site.com/user/blah http://www.site.com/page/bleh 

And your rules will look like this:

 Options -Indexes RewriteEngine On RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule ^user/([a-z0-9]+)$ /profile.php?username=$1 [L] RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule ^page/([a-z0-9]+)$ /display.php?page=$1 [L] 
+17
source
 Options -Indexes RewriteEngine On RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule ^user/([a-z0-9]+)$ /profile.php?username=$1 [N] RewriteRule ^page/([a-z0-9]+)$ /display.php?page=$1 [L] 

use [N] (hereinafter) continue adding rules to the same condition and [L] (last) to define the last rule

+2
source

I did it like that.

 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /domain/index.php/$1 [C] #second condition and rule RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /domain/subdir/index.php/$1 [L] 
0
source

Source: https://habr.com/ru/post/948494/


All Articles