nginx rewrite implements the URL jump method
- 2020-05-17 07:46:56
- OfStack
Recently, I often have to change the nginx configuration at work, and I have learned the usage of rewrite in nginx
URL jump
An URL jump is when a user accesses one URL and jumps it to another URL.
A common application scenario is to jump multiple domains to the same URL (e.g., jump an old domain to a new domain)
Skip the static file request to cdn
Jump to different sites (pc version, wap version) depending on the user's device.
The URL jump can be done with window.location, which js sets on the page
You can also set header by php
You can also use nginx's rewrite functionality
nginx rewrite module
rewrite is the static rewrite module for nginx
The basic usage is rewrite patten replace flag
patten is a regular expression. URL matching patten will be rewritten to replace. flag is optional
For example, jump the old domain name to the new domain name
server
{
listen 80;
server_name www.old.com;
rewrite ".*" http://www.new.com;
}
Keep the path when jumping to a new domain
server
{
listen 80;
server_name www.old.com;
rewrite "^/(.*)$" http://www.new.com/$1;
}
rewrite with location With the realization of the image file jump to cdn
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
expires 30d;
rewrite "^/uploadfile\/(.*)$" http://static.XXX.com/uploadfile/$1;
}
flag can be added after rewrite, and flag is marked as:
last is equivalent to the [L] mark in Apache, indicating completion of rewrite
break terminates the match and no longer matches the subsequent rule
The redirect return 302 temporary redirect address bar displays the address after the jump
permanent return 301 permanent redirect address bar will show the address after the jump