Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I currently have my URL for my video page rewritten like so

rewrite ^/watch/(.*) /video.php?vid_id=$1 last;

This makes the URL look like

www.site.com/watch/123456

instead of

www.site.com/video.php?vid_id=123456

I want to be able to add the title in the URL like so without it affecting the location and current behavior of the URL above

www.site.com/watch/123456/vid-title

I would also however, like to be able to still use www.site.com/watch/123456 or www.site.com/watch/123456/ to get to my video and therefore be equivalent to my original URL (have flexibility in the URL). Does anyone know how to do this with NGINX? Do I need multiple rewrites? I have tried combinations of multiple rewrites with no success. I have seen it done on many sites but am not sure how they accomplished it.

share|improve this question
    
What URL you want to rewrite www.site.com/watch/123456/vid-title to? –  quanta Oct 12 '11 at 4:06
    
I want it to go to www.site.com/video.php?vid_id=123456. I do not want the title add-on to affect my current url position of www.site.com/watch/123456. I just want the title added on for search engine optimization but I would also like the URL www.site.com/watch/123456 to work without the title added on. –  Scarface Oct 12 '11 at 4:17

1 Answer 1

up vote 1 down vote accepted

Try this:

rewrite ^/watch/([^/]+)/?(?:vid-title)?$ /video.php?vid_id=$1 last;
  • ([^/]+) matches any number of characters but not slash. You can use ([0-9]+) if you want.
  • The question mask ? makes the preceding regex is optional.
  • ?: tells the regex engine that this group should not create a backreference
share|improve this answer
    
You're the best quanta! Thanks so much for taking the time to help me out! How do you make vid-title a regex for any combination of this-is-my-title? Currently when I enter www.site.com/watch/123456/vid-title the url works but not if I enter www.site.com/watch/123456/some-other-vid-title –  Scarface Oct 12 '11 at 5:22
    
If your vid-title doesn't follow rules, you can use something like this ^/watch/([^/]+)/?(?:[^/]+)?/?$. –  quanta Oct 12 '11 at 6:00
    
Thanks again man. –  Scarface Oct 12 '11 at 14:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.