search
HomeOperation and MaintenanceNginxHow nginx redirects information

How nginx redirects information

Jun 22, 2019 pm 01:13 PM
nginxRedirect

How nginx redirects information

nginx 是一个灵活且高效的网络服务器,如果想要在nginx服务器中重定,你可以从下面挑选一个适合的方式。

简单且快速的 return

这是一个非常简单的设置方式,只需要个return语句就可以了

return 301 https://example.com$request_uri;

你需要把这段代码放到nginx配置文件的server代码块中,301是永久重定向,你也可以设置成302做一个临时重定向(不建议)。 

一个完整的例子:

return 301 https://example.com$request_uri;

正则表达式 rewrite

如果return不能满足你的复杂业务需求,你可以考虑下正则匹配重定向:

rewrite ^/foo/(bar)/(.*)$ https://$server_name/$1/$2 permanent;

同样这也是需要在server代码块中,其中permanent301永久跳转,若需要302可修改为redirect 

一个完整的例子:

server {
    listen 80;
    listen [::]:80;
    hostname example.com www.example.com;
    root /var/www/example.com/public;
    rewrite ^/foo/(bar)/(.*)$ $scheme://$server_name/$1/$2 permanent;
}

又如: 

server {
    listen       80;
    server_name   www.fangyongle.com  fangyongle.cn;
    if ($host != 'www.fangyongle.com' ) { 
        rewrite ^/(.*)$ https://www.fangyongle.com/$1 permanent; 
    } 
}

再如: 

# 根据文件类型设置过期时间
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
    if (-f $request_filename) {
       expires    1h;
       break;
    }
}

使用Maps 

如果你有一堆需要重定向的连接映射,你可以考虑在一个地方定义它,然后再通过if来手动判断重定向。

首先定义重定向链接映射redirect-map.conf

map $request_uri $redirect_uri {
    /about.html          /about-us;
    /customers.html      /our-customers;
    /products.html       /our-products;
}

然后在server代码块使用: 

include redirect-map.conf;
server {
    […]
    if ( $redirect_uri ) {
        return 301 $redirect_uri;
    }
}

映射也可以有一些语法: 

map $request_uri $redirect_uri {
    /about.html          /about-us;
    /customers.html      /our-customers;
    /products.html       /our-products;
    # Match any url that ends in products.html or producs.htm
    ~products\.html?$    /our-products;
    # case-insensitive version of the above
    ~*products\.html?$   /our-products;
    # A named capture that maps
    # e.g. product-1234.html into /products/item-1234/overview
    ~product-(?<sku>\d+)\.html   /products/item-$sku/overview;
}

一些实用的重定向例子 

http 重定向为 https

return 301 https://$host$request_uri;

统一规范域名

server_name example.com www.example.com example.net www.example.net _;
if ( $host != $server_name ) {
    return 301 $scheme://$server_name$request_uri;
}

含 www 和 不含 www 之间的重定向

# non-www to www
if ( $host !~ ^www\. ) {
    return 301 $scheme://www.$host$request_uri;
}
# www to non-www
if ( $host ~ ^www\.(?<domain>.+)$ ) {
    return 301 $scheme://$domain$request_uri;
}

附录

重定向中常用全局变量

$scheme       // HTTP方法(如http,https),如:http
$host   // 请求主机头字段,否则为服务器名称,如:blog.fangyongle.com
$server_name   // 服务器名称,如:blog.fangyongle.com
$request_uri   // 包含请求参数的原始URI,不包含主机名,如:/2018/81.html?a=1&b=2
$request_filename  // 当前请求的文件的路径名,由root或alias和URI request组合而成,如:/2013/81.htmlnginx 部分常用全局变量

nginx 部分常用全局变量

$remote_addr//获取客户端ip
$binary_remote_addr//客户端ip(二进制)
$remote_port//客户端port,如:50472
$remote_user//已经经过Auth Basic Module验证的用户名
$host//请求主机头字段,否则为服务器名称,如:blog.fangyongle.com
$request//用户请求信息,如:GET ?a=1&b=2 HTTP/1.1
$request_filename//当前请求的文件的路径名,由root或alias和URI request组合而成,如:/2013/81.html
$status//请求的响应状态码,如:200
$body_bytes_sent        // 响应时送出的body字节数数量。即使连接中断,这个数据也是精确的,如:40
$content_length       // 等于请求行的“Content_Length”的值
$content_type       // 等于请求行的“Content_Type”的值
$http_referer       // 引用地址
$http_user_agent      // 客户端agent信息,如:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36
$args     //与$query_string相同 等于当中URL的参数(GET),如a=1&b=2
$document_uri     //与$uri相同  这个变量指当前的请求URI,不包括任何参数(见$args) 如:/2018/81.html
$document_root     //针对当前请求的根路径设置值
$hostname     //如:centos53.localdomain
$http_cookie    //客户端cookie信息
$cookie_COOKIE    //cookie COOKIE变量的值
$is_args//如果有$args参数,这个变量等于”?”,否则等于”",空值,如?
$limit_rate//这个变量可以限制连接速率,0表示不限速
$query_string    // 与$args相同 等于当中URL的参数(GET),如a=1&b=2
$request_body   // 记录POST过来的数据信息
$request_body_file//客户端请求主体信息的临时文件名
$request_method      //客户端请求的动作,通常为GET或POST,如:GET
$request_uri      //包含请求参数的原始URI,不包含主机名,如:/2018/81.html?a=1&b=2
$scheme       //HTTP方法(如http,https),如:http
$uri//这个变量指当前的请求URI,不包括任何参数(见$args) 如:/2018/81.html
$request_completion//如果请求结束,设置为OK. 当请求未结束或如果该请求不是请求链串的最后一个时,为空(Empty),如:OK
$server_protocol//请求使用的协议,通常是HTTP/1.0或HTTP/1.1,如:HTTP/1.1
$server_addr//服务器IP地址,在完成一次系统调用后可以确定这个值
$server_name//服务器名称,如:blog.fangyongle.com
$server_port//请求到达服务器的端口号,如:80

Rewrite正则相关指令详解

nginx的rewrite相当于apache的rewriterule(大多数情况下可以把原有apache的rewrite规则加上引号就可以直接使用),它可以用在server,locationIF条件判断块中,命令格式如下:

rewrite <regex> <replacement> <flag>

正则表达式匹配 

  • ~ is a case-sensitive match

  • ~* is a case-insensitive match

  • ##!~ and !~* are case-sensitive mismatch and case-insensitive mismatch respectively

File and directory matching judgment

  • -f and !-f are used to determine whether the file exists

  • -d and !-d are used to determine whether the directory exists

  • -e and ! -e is used to determine whether the file or directory exists

  • -x and !-x is used to determine whether the file is executable

flag tag

  • last - This Flag is basically used.

  • break - Abortrewirte, no longer continue matching

  • redirect - Returns the HTTP status of temporary redirection 302

  • permanent - Returns the HTTP status of permanent redirection 301

Use

last and break to implement URI rewriting, and the browser address bar will remain unchanged. And there are subtle differences between the two:

  • The

    alias directive must be marked with last

  • ## When using the
  • proxy_pass

    command, you need to use the break mark

  • ##last
  • marked in this article

    rewrite After the rule is executed, the request will be re-initiated for the server{...} tag where it is located, and the break tag will terminate the matching after the matching of this rule is completed.

For more Nginx related technical articles, please visit the Nginx Tutorial column to learn!

The above is the detailed content of How nginx redirects information. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Using NGINX: Optimizing Website Performance and ReliabilityUsing NGINX: Optimizing Website Performance and ReliabilityMay 09, 2025 am 12:19 AM

NGINX can improve website performance and reliability by: 1. Process static content as a web server; 2. forward requests as a reverse proxy server; 3. allocate requests as a load balancer; 4. Reduce backend pressure as a cache server. NGINX can significantly improve website performance through configuration optimizations such as enabling Gzip compression and adjusting connection pooling.

NGINX's Purpose: Serving Web Content and MoreNGINX's Purpose: Serving Web Content and MoreMay 08, 2025 am 12:07 AM

NGINXserveswebcontentandactsasareverseproxy,loadbalancer,andmore.1)ItefficientlyservesstaticcontentlikeHTMLandimages.2)Itfunctionsasareverseproxyandloadbalancer,distributingtrafficacrossservers.3)NGINXenhancesperformancethroughcaching.4)Itofferssecur

NGINX Unit: Streamlining Application DeploymentNGINX Unit: Streamlining Application DeploymentMay 07, 2025 am 12:08 AM

NGINXUnit simplifies application deployment with dynamic configuration and multilingual support. 1) Dynamic configuration can be modified without restarting the server. 2) Supports multiple programming languages, such as Python, PHP, and Java. 3) Adopt asynchronous non-blocking I/O model to improve high concurrency processing performance.

NGINX's Impact: Web Servers and BeyondNGINX's Impact: Web Servers and BeyondMay 06, 2025 am 12:05 AM

NGINX initially solved the C10K problem and has now developed into an all-rounder who handles load balancing, reverse proxying and API gateways. 1) It is well-known for event-driven and non-blocking architectures and is suitable for high concurrency. 2) NGINX can be used as an HTTP and reverse proxy server, supporting IMAP/POP3. 3) Its working principle is based on event-driven and asynchronous I/O models, improving performance. 4) Basic usage includes configuring virtual hosts and load balancing, and advanced usage involves complex load balancing and caching strategies. 5) Common errors include configuration syntax errors and permission issues, and debugging skills include using nginx-t command and stub_status module. 6) Performance optimization suggestions include adjusting worker parameters, using gzip compression and

Nginx Troubleshooting: Diagnosing and Resolving Common ErrorsNginx Troubleshooting: Diagnosing and Resolving Common ErrorsMay 05, 2025 am 12:09 AM

Diagnosis and solutions for common errors of Nginx include: 1. View log files, 2. Adjust configuration files, 3. Optimize performance. By analyzing logs, adjusting timeout settings and optimizing cache and load balancing, errors such as 404, 502, 504 can be effectively resolved to improve website stability and performance.

Deploying Applications with NGINX Unit: A GuideDeploying Applications with NGINX Unit: A GuideMay 04, 2025 am 12:03 AM

NGINXUnitischosenfordeployingapplicationsduetoitsflexibility,easeofuse,andabilitytohandledynamicapplications.1)ItsupportsmultipleprogramminglanguageslikePython,PHP,Node.js,andJava.2)Itallowsdynamicreconfigurationwithoutdowntime.3)ItusesJSONforconfigu

NGINX and Web Hosting: Serving Files and Managing TrafficNGINX and Web Hosting: Serving Files and Managing TrafficMay 03, 2025 am 12:14 AM

NGINX can be used to serve files and manage traffic. 1) Configure NGINX service static files: define the listening port and file directory. 2) Implement load balancing and traffic management: Use upstream module and cache policies to optimize performance.

NGINX vs. Apache: Comparing Web Server TechnologiesNGINX vs. Apache: Comparing Web Server TechnologiesMay 02, 2025 am 12:08 AM

NGINX is suitable for handling high concurrency and static content, while Apache is suitable for dynamic content and complex URL rewrites. 1.NGINX adopts an event-driven model, suitable for high concurrency. 2. Apache uses process or thread model, which is suitable for dynamic content. 3. NGINX configuration is simple, Apache configuration is complex but more flexible.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software