1

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.

2
  • What URL you want to rewrite www.site.com/watch/123456/vid-title to?
    – quanta
    Oct 12, 2011 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, 2011 at 4:17

1 Answer 1

2

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
2
  • 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, 2011 at 5:22
  • If your vid-title doesn't follow rules, you can use something like this ^/watch/([^/]+)/?(?:[^/]+)?/?$.
    – quanta
    Oct 12, 2011 at 6:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .