简体   繁体   中英

.htaccess Multiple Rewrite Rules / Prioritizing

Here is my current htaccess file:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.website\.com [NC]
RewriteCond %{HTTP_HOST} ([^.]+)\.website\.com [NC]
RewriteRule ^(.*)$ http://www.website.com/gotourl.php?urlid=?%1 [L]
RewriteRule    ^(\w+)$ ./gotourl.php?urlid=$1    [NC,L]    
RewriteRule    ^(\w+)/$ ./gotourl.php?urlid=$1    [NC,L]   

The website in question is a URL shortener I'm working on for testing/developing and personal use. The above code may not be ideal as I'm not that familiar with .htaccess and made this via googling and testing. This does what I want it to for the URL shortening aspect:

http://website.com/1234 -> http://website.com/gotourl.php?urlid=1234
http://website.com/1234/ -> http://website.com/gotourl.php?urlid=1234

The problem is I cannot figure out how to get it to ignore certain directories. I want specific directories to go to specific pages:

http://website.com/img (or) http://website.com/img/ -> http://website.com/img.php
http://website.com/img/1234 (or) http://website.com/img/1234/ -> http://website.com/viewimage.php?imgid=1234

The main problem is I don't know how to properly do this and the ways I've tried to do it would always rewrite to:

http://website.com/gotourl.php?urlid=XXXX

or end up in an infinite loop of redirects instead of going to the specific page I'm wanting. Any help is appreciated.

In essence I'm looking for help writing my htaccess to do the following:

URL user visits -> URL user sees
http://website.com/img -> http://website.com/img.php
http://website.com/img/XXXX -> http://website.com/viewimage.php?imgid=XXXX
http://website.com/XXXX -> http://website.com/gotourl.php?urlid=XXXX

All paths should work with or without the trailing slash.

Looking for help to get it to do that with maybe a bit of explanation as to what each line actually means so I can learn from it.

The main thing you want to change, is making your rule more specific. Your shortened url can probably not contain a slash or a dot, so you could change both the url shortening url's to: RewriteRule ^([^/\\.]+)/?$ gotourl.php?urlid=$1 [NC,L] . You'll need to prevent 'gotourl.php' from matching that though. The rule for img alone is more specific and should be done first. The rule for img/something is a little less specific and can be anywhere.

RewriteEngine On

RewriteRule ^img/?$ img.php [L]
RewriteRule ^img/([^/]+)/?$ viewimage.php?imgid=$1 [L]
RewriteCond %{HTTP_HOST} !^www\.website\.com [NC]
RewriteCond %{HTTP_HOST} ([^.]+)\.website\.com [NC]
RewriteRule ^(.*)$ http://www.website.com/gotourl.php?urlid=%1 [L]
RewriteRule ^([^/\.]+)/?$ gotourl.php?urlid=$1 [NC,L]

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