简体   繁体   中英

Creating static, SEO friendly URLs with mod-rewrite

Okay I have revised a previous question to make my intentions more clear and hopefully to help others wishing to do similar things.

Let's say I have a digital download store, I want my URL's to look like this:

downloads.com/music/this-song-name/3873         // A url to a unique track
downloads.com/music/featured-stuff      // A url that links to unique content
downloads.com/music                 // The homepage for that section

I could also have a url like this

downloads.com/videos/this-video/3876

etc.

Now, Server side, PHP does all the work. It takes the URL:

downloads.com/?a=music&b=this-song-name&c=37863 // load page a, get ID c from database 

OR

 downloads.com/?a=music     // Just load the default music page

I need .htaccess to change

url.com/?a=1&b=2&c=3` 

to

 url.com/1/2/3

a,b and c are fixed and will be the only parameters used to parse data (eg you won't find ?f=music anytime soon)

One problem I've had is, I can get it to work if all three parameters are present but it will not work if one is taken away.

I'm no REGEX expert and mod re-write hates me, I was hoping someone out there could help create a beautiful line of code that would aid me and others curious to do so.

Thanks

I figure that you already have the basic mod rewrite rules.

The code you are looking for is this:

RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/?$ index.php?a=$1&b=$2&c=$3
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/?$ index.php?a=$1&b=$2
RewriteRule ^([a-zA-Z0-9_-]+)/?$ index.php?a=$1

Regex explanation

^                # Matches the start of the string (the URL)
(                # Indicates the start of a capturing group (in this case the thing we want to replace)
[a-zA-Z0-9_-]+   # Matches 1 or more letters, numbers, underscore's and -'s (+ = 1 or more * = 0 or more) 
)                # Indicates the end of the capturing group
/?               # Matches 0 or 1 times the '/' symbol 
$                # Matches the end of the string (the URL)

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