nginx 配置多个server与多个location

配置多个Server

(主要针对于不同端口号访问多个项目)

		server {
     		listen       80;
     		# 如 www.baidu.com 一般二级域名
     		server_name  xxx.xxx.xxx;
			# 80端口下的所有路径都代理到这
	        location / {
	        	# 访问路径(相对路径)
				root   html/main;
				# 首页
				index  index.html;
				# 指的是 查找 $uri 存在则访问 $uri ,不存在则再次去请求 $uri/ ,
				#  不存在则依次往下一个值(/index.html)请求 
				try_files $uri $uri/ /index.html;
				# 错误页面
				error_page 404 /index.html;
	        	}
    	}
		
		server {
       		listen       9529;
       		server_name  xxx;
    
        	location / {
					root   html/app-itsm;
					index  index.html;
                	try_files $uri $uri/ /index.html;
					error_page 404 /index.html;	
          		}
			# 允许跨域
			add_header Access-Control-Allow-Credentials true;
        	add_header Access-Control-Allow-Origin *;

        }

同 Server配置多个 localtion

(主要用于一个端口号,访问多个网页或项目)

		server {
       		listen       9529;
       		# 一般域名
       		server_name  xxx;
       		
			# ^~/gateway/ 指的是包含 /gateway/ 路径的 ^是必须的,~指的是不管什么字符都可
			# 反向代理
			location ^~/gateway/ {
				# 代理后的请求头设置
				proxy_set_header Host $host;
	    		proxy_set_header X-Real-IP $remote_addr;
	    		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	       		proxy_set_header X-Forwarded-Proto $scheme;
	       		proxy_set_header X-Forwarded-Host $host;
	       		proxy_set_header X-Forwarded-Port $server_port;
	        	# 8888/ 中的 / 是为了去掉 /gateway/ 不加 / 反向代理后还会带有 /gateway/
				proxy_pass http://10.26.180.44:8888/;
				# 开启跨域
				add_header Access-Control-Allow-Credentials true;
	        	add_header Access-Control-Allow-Origin *;
				add_header Access-Control-Allow-Methods *;
				add_header Access-Control-Allow-Headers *;
				
			}

			# 重定向
			location ^~/redirect/ {
				#重定向到具体网站 ^~/redirect/ 与 redirect 不可少
                rewrite ^~/redirect/ http://xxxxx redirect;
             }
    
        	location / {
				root   html/app-itsm;
				index  index.html;
				# 指的是 查找 $uri 存在则访问 $uri ,不存在则再次去请求 $uri/ ,
				#  不存在则依次往下一个值(/index.html)请求 
               	try_files $uri $uri/ /index.html;
               	# 错误页面
				error_page 404 /index.html;	
         	}
			# 允许跨域
			add_header Access-Control-Allow-Credentials true;
        	add_header Access-Control-Allow-Origin *;

        }
<think>我们正在讨论Nginx配置多个location块的使用方法。根据引用[1]和引用[2],配置多个location时,主要是通过不同的匹配规则来将不同的请求路由到不同的处理逻辑(如静态文件服务、代理转发等)。以下是详细的配置方法和使用技巧: ### 📌 一、Location 匹配规则优先级 Nginxlocation 匹配遵循以下优先级顺序(从高到低): 1. `=` 精确匹配 2. `^~` 前缀匹配(一旦匹配,不再检查正则) 3. `~` 和 `~*` 正则匹配(区分大小写和不区分大小写) 4. 普通前缀匹配(按配置文件顺序,但被正则匹配覆盖) 5. `/` 通用匹配 ### 🛠️ 二、多 location 配置实践 #### 1. 基础配置结构 ```nginx server { listen 80; server_name example.com; # 规则1: 首页精确匹配(最高优先级) location = / { proxy_pass http://backend/home; } # 规则2: 静态文件目录匹配(优先级高于正则) location ^~ /static/ { root /var/www/static; expires 30d; # 缓存控制 } # 规则3: 图片等静态资源(正则匹配) location ~* \.(jpg|png|css|js)$ { root /var/www/assets; access_log off; # 关闭日志减少IO } # 规则4: 通用代理规则(兜底处理) location / { proxy_pass http://backend/app; } } ``` #### 2. 关键参数解析 | 配置指令 | 作用说明 | |----------------|--------------------------------------------------------------------------| | `root` | 定义资源根目录,最终路径 = `root` + `location` 路径 | | `alias` | 路径别名,**末尾必须加/**(引用[2]示例) | | `proxy_pass` | 指定代理的上游服务地址 | | `expires` | 设置静态资源缓存时间 | | `access_log` | 控制日志记录(对静态资源可关闭) | #### 3. `root` vs `alias` 区别(引用[2]示例) - **`root` 示例**: ```nginx location /reports/ { root /opt/app/data; # 请求 /reports/index.html 将访问 /opt/app/data/reports/index.html } ``` - **`alias` 示例**: ```nginx location /docs/ { alias /opt/app/documentation/; # 请求 /docs/tutorial.html 将访问 /opt/app/documentation/tutorial.html } ``` > ⚠️ 关键区别:`alias` 会**丢弃** location 中匹配的部分,而 `root` 会**保留**。 ### 🔍 三、配置调试技巧 1. **测试匹配顺序**: ```nginx # 在 location 中添加调试头 add_header X-Location-Matched "static" always; ``` 2. **日志分析**: ```nginx error_log /var/log/nginx/debug.log debug; # 启用调试日志 ``` ### ⚠️ 四、常见错误避免 1. **正则冲突**: ```nginx # 错误:两个正则冲突导致不可预测行为 location ~ /user/.+\.html$ { ... } location ~ /user/profile { ... } # 可能不会被匹配到 # 修正:调整顺序或改用前缀匹配 location ^~ /user/profile { ... } # 优先处理 location ~ /user/.+\.html$ { ... } ``` 2. **斜杠处理**: - `proxy_pass` 后带 `/`:**替换整个路径** `location /api/ { proxy_pass http://backend/; }` `请求 /api/user → 后端 /user` - 不带 `/`:**追加路径** `location /api/ { proxy_pass http://backend; }` `请求 /api/user → 后端 /api/user` ### 🌐 五、多 location 协作流程图 ```mermaid graph TD A[请求] --> B{是否精确匹配?} B -->|是| C[执行 = 规则] B -->|否| D{是否 ^~ 匹配?} D -->|是| E[执行 ^~ 规则] D -->|否| F{正则匹配?} F -->|是| G[按顺序执行首个匹配的正则] F -->|否| H[执行普通前缀匹配] H --> I{有匹配?} I -->|是| J[执行匹配规则] I -->|否| K[返回 404] ``` ### 📚 六、最佳实践建议 1. **静态资源优先**:将静态资源 location 放在动态规则之前(利用 `^~` 避免正则检查) 2. **避免过多正则**:正则匹配效率低于前缀匹配 3. **兜底规则**:始终配置 `location /` 作为最后处理项 4. **缓存策略**:对静态资源设置 `expires` 和 `Cache-Control` ### ❓ 相关问题 §§相关问题§§ 1. 如何解决Nginx location匹配冲突问题? 2. Nginx中root和alias指令的区别详解? 3. 如何优化Nginx静态资源服务性能? 4. Nginx代理转发时路径修改有哪些技巧? 5. 如何配置Nginx的访问日志记录规则? </think> ## 📝 Nginx配置多个location的使用方法详解 在Nginx配置多个`location`块是实现复杂路由规则的核心功能,允许根据不同的URL路径进行差异化处理。以下是详细配置方法和实践技巧: --- ### 🔧 一、基础配置结构 ```nginx server { listen 80; server_name example.com; # 1. 首页精确匹配(最高优先级) location = / { root /var/www/home; index index.html; } # 2. 静态文件目录匹配 location ^~ /static/ { root /var/www; expires 30d; # 缓存控制 } # 3. 动态请求代理 location /api/ { proxy_pass http://backend_server/; proxy_set_header Host $host; } # 4. 图片资源处理(正则匹配) location ~* \.(jpg|png|gif)$ { root /var/www/images; access_log off; # 关闭日志减少IO } # 5. 通用兜底规则 location / { root /var/www/main; try_files $uri $uri/ =404; } } ``` --- ### ⚙️ 二、关键匹配规则解析 | **匹配类型** | **语法** | **优先级** | **使用场景** | |--------------------|------------------|------------|-----------------------------| | 精确匹配 | `location = /path` | 最高 (1) | 首页等特定路径 | | 前缀匹配 | `location ^~ /dir/` | 高 (2) | 静态资源目录 | | 正则匹配(区分大小写) | `location ~ \.php$` | 中 (3) | 动态请求处理 | | 正则匹配(不区分) | `location ~* \.jpg$` | 中 (3) | 图片/CSS等静态资源 | | 通用前缀匹配 | `location /` | 低 (4) | 兜底规则 | > 📌 **优先级说明**:数字越小优先级越高,相同优先级按配置文件顺序匹配 --- ### 🛠 三、核心配置技巧 #### 1. `root` vs `alias` 区别(引用[2]) ```nginx # 使用root(完整路径拼接) location /reports/ { root /opt/app/data; # 请求/reports/index.html → /opt/app/data/reports/index.html } # 使用alias(路径替换) location /docs/ { alias /opt/app/documentation/; # 请求/docs/tutorial.html → /opt/app/documentation/tutorial.html } ``` > ⚠️ 关键区别:`alias` 末尾**必须加斜杠**,且会丢弃匹配的URI部分 #### 2. 代理转发配置 ```nginx location /api/ { proxy_pass http://backend:8080/; # 末尾斜杠会移除/api前缀 # 常用代理头设置 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } ``` #### 3. 静态资源优化 ```nginx location ~* \.(js|css|png)$ { root /var/www/static; # 性能优化参数 expires 365d; # 长期缓存 add_header Cache-Control "public"; gzip_static on; # 预压缩支持 access_log off; # 关闭访问日志 } ``` --- ### ⚠️ 四、常见问题解决方案 #### 1. 匹配冲突问题 ```nginx # 错误:两个正则冲突 location ~ /user/.+\.html$ { ... } location ~ /user/profile { ... } # 永远不会执行 # 修正方案:改用前缀匹配提升优先级 location ^~ /user/profile { ... } # 优先处理 location ~ /user/.+\.html$ { ... } ``` #### 2. 路径拼接问题 ```nginx # 请求 /static/img/logo.png 时 location /static/ { # root方式:/var/www/static/ + /static/img/logo.png → 错误! alias /var/www/static_files/; # 正确 → /var/www/static_files/img/logo.png } ``` --- ### 📊 五、配置调试流程 1. **检查匹配顺序**: ```bash nginx -T # 查看完整配置 ``` 2. **添加调试头**: ```nginx location /test { add_header X-Matched-Location "test" always; ... } ``` 3. **日志分析**: ```nginx error_log /var/log/nginx/debug.log debug; # 启用debug日志 ``` --- ### 📚 六、最佳实践原则 1. **从具体到通用**:精确匹配 → 前缀匹配 → 正则匹配 → 通用匹配 2. **静态优先动态**:将静态资源处理放在动态代理之前 3. **限制正则数量**:过多正则影响性能,优先用前缀匹配 4. **必配兜底规则**:始终保留`location /`处理未匹配请求 --- ### ❓ 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值