简体   繁体   中英

.htaccess rewrite: Same rule, different location

Below is a list of some rewrite rules that I want to have for my index page:

www.website.com/index.php?page=page1 -> www.website.com/page1
www.website.com/index.php?page=page2 -> www.website.com/page2

But I also have a profile page where I want the following rules:

www.website.com/profile.php?user=user1 -> www.website.com/user1
www.website.com/profile.php?user=user2 -> www.website.com/user2

Both use the same rule, but have different locations. For the index page, there are only 2 possible parameters, page1 and page2 , but the profile page's parameters can be anything.

How can I achieve these rewrite rules without doing something like www.website.com/page/page1 and www.website.com/user/user1 . I need those exact rules as shown above.

My thought is adding a rule (I'm not sure how) above the user rules to check that the URL doesn't have page1 or page2 .

Since you only have 2 possible pages, you can get away with something like this:

RewriteEngine On

RewriteRule ^(page1|page2)$ /index.php?page=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ /profile.php?user=$1 [L]

If you need to redirect externally as well, add these (right below RewriteEngine On ):

RewriteCond %{THE_REQUEST} \ /+index\.php\?page=(page1|page2)
RewriteRule ^ /%1? [L,R]

RewriteCond %{THE_REQUEST} \ /+profile\.php\?user=([^&\ ]+)
RewriteRule ^ /%1? [L,R]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM