Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

url rewriting - How to write a url rewrite in nginx?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...