Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 270
murvinlai Avatar asked Dec 01 '10 21:12

murvinlai


People also ask

What is return 301 in NGINX?

Permanent redirects such as NGINX 301 Redirect simply makes the browser forget the old address entirely and prevents it from attempting to access that address anymore. These redirects are very useful if your content has been permanently moved to a new location, like when you change domain names or servers.

What is $URI in NGINX?

According to nginx documentation, $uri and $document_uri contain the normalized URI whereas the normalization includes URL decoding the URI. Every file requested under /static/ folder will be redirect to another server, in this case example.com.


2 Answers

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; 
like image 80
TheBlackBenzKid Avatar answered Sep 24 '22 07:09

TheBlackBenzKid


Try this,

server {   server_name www.myweb.com;   rewrite ^/like/(.*) http://www.myweb.com/item.php?itemid=$1 permanent; } 
like image 24
Satys Avatar answered Sep 24 '22 07:09

Satys