30

I want people type in http://www.myweb.com/like/1234456 will redirect to http://www.myweb.com/item.php?itemid=1234456

I wrote something like this in the config but it doesn't work.

location = ^~/like/ {
                rewrite ^1234456  ../likeitem.php?item=1234456break;
                return 403;
        }

this is just a test. I haven't used the $ matching yet.

I also restart my ngnix server but still.. it doesn't do the redirect.

shilovk
  • 11,718
  • 17
  • 75
  • 74
murvinlai
  • 48,919
  • 52
  • 129
  • 177

2 Answers2

60

The code above will not work because of a missing $ and poor use of the return command.

The code below works with Nginx, including version 0.8.54.

Format below is :

  1. DesiredURL
  2. Actual URL
  3. Nginx_Rule

They must be inside location / {}

http://example.com/notes/343
http://example.com/notes.php?id=343

rewrite ^/notes/(.*)$ /notes.php?id=$1 last;

http://example.com/users/BlackBenzKid
http://example.com/user.php?username=BlackBenzKid

rewrite ^/users/(.*)$ /user.php?username=$1 last;

http://example.com/top
http://example.com/top.php

rewrite ^/top?$ /top.php last;

Complex and further

http://example.com/users/BlackBenzKid/gallery
http://example.com/user.php?username=BlackBenzKid&page=gallery

rewrite ^/users/(.*)/gallery$ /user.php?username=$1&page=gallery last;
TheBlackBenzKid
  • 26,324
  • 41
  • 139
  • 209
  • 1
    @the0ther lol appreciate the kind words. Most of the information is on the Nginx Wiki and slowly slowly.. nginx seems to become more unified and central in terms of documentation and resources. – TheBlackBenzKid Mar 25 '13 at 10:00
  • 3
    How will BlackBenzKid be converted into `id=1`? Or am I missing anything? – Madara's Ghost Jul 02 '13 at 06:49
  • 3
    @TheBlackBenzKid: How is it connected then? Who makes the maps "users/BlackBenzKid/gallery" to "user.php?username=1&page=gallery"? – Madara's Ghost Jul 03 '13 at 14:56
  • 2
    @MadaraUchiha my friend it was just an example of using my SEO variables and querystring combinations, it was just off hand to get the point. Regards – TheBlackBenzKid Jul 04 '13 at 08:12
  • 2
    @SecondRikudo I have an edit queued for review that should explain, I think there were two errors in the examples. – Pablo Mar 29 '15 at 21:42
  • 5
    huge THANKS to the author of this post. i'd been searching on google how to do such a simple thing on nginx for an hour and found only a couple of about a meter length articles talking about something impossible to understand for a beginner. finally i've found this answer on SO that was clear and made a great introduction to experimenting with nginx url rewrite capabilities on my own. big BIG THANKS man!!! – Salivan Jul 07 '15 at 18:57
3

Try this,

server {
  server_name www.myweb.com;
  rewrite ^/like/(.*) http://www.myweb.com/item.php?itemid=$1 permanent;
}
Satys
  • 2,319
  • 1
  • 20
  • 26