简体   繁体   中英

htacces rewrite rule conflict with other url

I have the Following htaccess file. the problem is while goto page2.php its going to page1.php like this page3.php goes to page1.php.

Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteBase /bookshow/


RewriteCond %{THE_REQUEST} /page1\.php\?name=([^\s&]+) [NC]
RewriteRule ^ %1? [R=302,L]

RewriteCond %{THE_REQUEST} /page2\.php\?id=([^\s&]+) [NC]
RewriteRule ^ %1? [R=302,NE,L]


RewriteCond %{THE_REQUEST} /page3\.php\?cat=([^\s&]+) [NC]
RewriteRule ^ %1? [R=302,NE,L]


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/?$ page1.php?name=$1 [L,NE,QSA,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/?$ page2.php?id=$1 [L,NE,QSA,NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?$ page3.php?cat=$1 [L,NE,QSA,NC]

As Panama Jack stated, the server cannot simply guess which rewrite needs to occur after the page has been redirected, simply because the patterns for each of your three rules are exactly the same . As such, the first rule will always execute, and nothing else will.

To tackle this, use the following code instead:

RewriteEngine on

RewriteBase /bookshow/

# Step 1: Redirect all pagex.php?... to new URIs

RewriteCond %{QUERY_STRING} cat=([^\s&]+)$ [NC]
RewriteRule ^page1.php$ cat/%1? [R=302,NE,L]

RewriteCond %{QUERY_STRING} name=([^\s&]+)$ [NC]
RewriteRule ^page2.php$ name/%1? [R=302,NE,L]

RewriteCond %{QUERY_STRING} id=([^\s&]+)$ [NC]
RewriteRule ^page3.php$ id/%1? [R=302,NE,L]

# Step 2: Rewrite cat/something, name/something, id/something to the actual pages

RewriteRule ^cat/([^/]*)/?$ page1.php?cat=$1&r [L,NE,QSA,NC]
RewriteRule ^name/([^/]*)/?$ page2.php?name=$1&r [L,NE,QSA,NC]
RewriteRule ^id/([^/]*)/?$ page3.php?id=$1&r [L,NE,QSA,NC]

Further Explanation:

In the first step , we're checking which page is being access with what query string. If there is a match, redirect to the new URI.

For example, page1.php?cat=hello will redirect to cat/hello .

Then, in the second step, we rewrite these new URIs to the already-existing pages, and append &r to the query string so we avoid a redirect loop. This &r is basically redundant, and acts like a dummy.

For example, cat/hello will internally rewrite to page1.php?cat=hello&r .

Updated: I have removed RewriteCond %{REQUEST_FILENAME} !-f and RewriteCond %{REQUEST_FILENAME} !-d from the code as well - these are not needed. Feel free to put them back if you ever land up needing them.

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