search
HomeOperation and MaintenanceNginxHow to use proxy_pass in Nginx

How to use proxy_pass in Nginx

一、proxy_pass的nginx官方指南

nginx中有两个模块都有proxy_pass指令。

ngx_http_proxy_module的proxy_pass:

语法: proxy_pass URL;
场景: location, if in location, limit_except
说明: 设置后端代理服务器的•协议(protocol)和地址(address),以及location中可以匹配的一个可选的URI。协议可以是"http"或"https"。地址可以是一个域名或ip地址和端口,或者一个 unix-domain socket 路径。  
详见官方文档: http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_passURI的匹配,本文第四部分•重点讨论。

ngx_stream_proxy_module的proxy_pass:

语法: proxy_pass address;
场景: server
说明: 设置后端代理服务器的地址。这个地址(address)可以是一个域名或ip地址和端口,或者一个 unix-domain socket路径。  
详见官方文档: http://nginx.org/en/docs/stream/ngx_stream_proxy_module.html#proxy_pass

二、两个proxy_pass的关系和区别

在两个模块中,两个proxy_pass都是用来做后端代理的指令。

ngx_stream_proxy_module模块的proxy_pass指令只能在server段使用使用, 只需要提供域名或ip地址和端口。可以理解为端口转发,可以是tcp端口,也可以是udp端口。

ngx_http_proxy_module模块的proxy_pass指令需要在location段,location中的if段,limit_except段中使用,处理需要提供域名或ip地址和端口外,还需要提供协议,如”http”或”https”,还有一个可选的uri可以配置。

三、proxy_pass的具体用法

ngx_stream_proxy_module模块的proxy_pass指令

server {
   listen 127.0.0.1:12345;
   proxy_pass 127.0.0.1:8080;
}

server {
   listen 12345;
   proxy_connect_timeout 1s;
   proxy_timeout 1m;
   proxy_pass example.com:12345;
}

server {
   listen 53 udp;
   proxy_responses 1;
   proxy_timeout 20s;
   proxy_pass dns.example.com:53;
}

server {
   listen [::1]:12345;
   proxy_pass unix:/tmp/stream.socket;
}

ngx_http_proxy_module模块的proxy_pass指令

server {
   listen      80;
   server_name www.test.com;

   # 正常代理,不修改后端url的   location /some/path/ {
       proxy_pass http://127.0.0.1;
   }

   # 修改后端url地址的代理(本例后端地址中,最后带了一个斜线)   location /testb {
       proxy_pass http://www.other.com:8801/;
   }

   # 使用 if in location   location /google {
       if ( $geoip_country_code ~ (RU|CN) ) {
           proxy_pass http://www.google.hk;
       }
   }

   location /yongfu/ {
       # 没有匹配 limit_except 的,代理到 unix:/tmp/backend.socket:/uri/       proxy_pass http://unix:/tmp/backend.socket:/uri/;;

       # 匹配到请求方法为: PUT or DELETE, 代理到9080       limit_except PUT DELETE {
           proxy_pass http://127.0.0.1:9080;
       }
   }

}

四、proxy_pass后,后端服务器的url(request_uri)情况分析

server {
   listen      80;
   server_name www.test.com;

   # 情形A   # 访问 http://www.test.com/testa/aaaa   # 后端的request_uri为: /testa/aaaa   location ^~ /testa/ {
       proxy_pass http://127.0.0.1:8801;
   }
   
   # 情形B   # 访问 http://www.test.com/testb/bbbb   # 后端的request_uri为: /bbbb   location ^~ /testb/ {
       proxy_pass http://127.0.0.1:8801/;
   }

   # 情形C   # 下面这段location是正确的   location ~ /testc {
       proxy_pass http://127.0.0.1:8801;
   }

   # 情形D   # 下面这段location是错误的   #   # nginx -t 时,会报如下错误:   #   # nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular   # expression, or inside named location, or inside "if" statement, or inside   # "limit_except" block in /opt/app/nginx/conf/vhost/test.conf:17   #   # 当location为正则表达式时,proxy_pass 不能包含URI部分。本例中包含了"/"   location ~ /testd {
       proxy_pass http://127.0.0.1:8801/;   # 记住,location为正则表达式时,不能这样写!!!   }

   # 情形E   # 访问 http://www.test.com/ccc/bbbb   # 后端的request_uri为: /aaa/ccc/bbbb   location /ccc/ {
       proxy_pass http://127.0.0.1:8801/aaa$request_uri;
   }

   # 情形F   # 访问 http://www.test.com/namea/ddd   # 后端的request_uri为: /yongfu?namea=ddd   location /namea/ {
       rewrite    /namea/([^/]+) /yongfu?namea=$1 break;
       proxy_pass http://127.0.0.1:8801;
   }

   # 情形G   # 访问 http://www.test.com/nameb/eee   # 后端的request_uri为: /yongfu?nameb=eee   location /nameb/ {
       rewrite    /nameb/([^/]+) /yongfu?nameb=$1 break;
       proxy_pass http://127.0.0.1:8801/;
   }

   access_log /data/logs/www/www.test.com.log;
}

server {
   listen      8801;
   server_name www.test.com;
   
   root        /data/www/test;
   index       index.php index.html;

   rewrite ^(.*)$ /test.php?u=$1 last;

   location ~ \.php$ {
       try_files $uri =404;
       fastcgi_pass unix:/tmp/php-cgi.sock;
       fastcgi_index index.php;
       include fastcgi.conf;
   }

   access_log /data/logs/www/www.test.com.8801.log;
}

文件: /data/www/test/test.php

echo '$_SERVER[REQUEST_URI]:' . $_SERVER['REQUEST_URI'];

通过查看 $_SERVER[‘REQUEST_URI’] 的值,我们可以看到每次请求的后端的request_uri的值,进行验证。

The above is the detailed content of How to use proxy_pass in Nginx. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
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.

NGINX and Apache: Deployment and ConfigurationNGINX and Apache: Deployment and ConfigurationMay 01, 2025 am 12:08 AM

NGINX and Apache each have their own advantages, and the choice depends on the specific needs. 1.NGINX is suitable for high concurrency, with simple deployment, and configuration examples include virtual hosts and reverse proxy. 2. Apache is suitable for complex configurations and is equally simple to deploy. Configuration examples include virtual hosts and URL rewrites.

NGINX Unit's Purpose: Running Web ApplicationsNGINX Unit's Purpose: Running Web ApplicationsApr 30, 2025 am 12:06 AM

The purpose of NGINXUnit is to simplify the deployment and management of web applications. Its advantages include: 1) Supports multiple programming languages, such as Python, PHP, Go, Java and Node.js; 2) Provides dynamic configuration and automatic reloading functions; 3) manages application lifecycle through a unified API; 4) Adopt an asynchronous I/O model to support high concurrency and load balancing.

NGINX: An Introduction to the High-Performance Web ServerNGINX: An Introduction to the High-Performance Web ServerApr 29, 2025 am 12:02 AM

NGINX started in 2002 and was developed by IgorSysoev to solve the C10k problem. 1.NGINX is a high-performance web server, an event-driven asynchronous architecture, suitable for high concurrency. 2. Provide advanced functions such as reverse proxy, load balancing and caching to improve system performance and reliability. 3. Optimization techniques include adjusting the number of worker processes, enabling Gzip compression, using HTTP/2 and security configuration.

NGINX vs. Apache: A Look at Their ArchitecturesNGINX vs. Apache: A Look at Their ArchitecturesApr 28, 2025 am 12:13 AM

The main architecture difference between NGINX and Apache is that NGINX adopts event-driven, asynchronous non-blocking model, while Apache uses process or thread model. 1) NGINX efficiently handles high-concurrent connections through event loops and I/O multiplexing mechanisms, suitable for static content and reverse proxy. 2) Apache adopts a multi-process or multi-threaded model, which is highly stable but has high resource consumption, and is suitable for scenarios where rich module expansion is required.

NGINX vs. Apache: Examining the Pros and ConsNGINX vs. Apache: Examining the Pros and ConsApr 27, 2025 am 12:05 AM

NGINX is suitable for handling high concurrent and static content, while Apache is suitable for complex configurations and dynamic content. 1. NGINX efficiently handles concurrent connections, suitable for high-traffic scenarios, but requires additional configuration when processing dynamic content. 2. Apache provides rich modules and flexible configurations, which are suitable for complex needs, but have poor high concurrency performance.

NGINX and Apache: Understanding the Key DifferencesNGINX and Apache: Understanding the Key DifferencesApr 26, 2025 am 12:01 AM

NGINX and Apache each have their own advantages and disadvantages, and the choice should be based on specific needs. 1.NGINX is suitable for high concurrency scenarios because of its asynchronous non-blocking architecture. 2. Apache is suitable for low-concurrency scenarios that require complex configurations, because of its modular design.

NGINX Unit: Key Features and CapabilitiesNGINX Unit: Key Features and CapabilitiesApr 25, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports multiple programming languages ​​and provides functions such as dynamic configuration, zero downtime updates and built-in load balancing. 1. Dynamic configuration: You can modify the configuration without restarting. 2. Multilingual support: compatible with Python, Go, Java, PHP, etc. 3. Zero downtime update: Supports application updates that do not interrupt services. 4. Built-in load balancing: Requests can be distributed to multiple application instances.

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use