f
fatelyh
V1
2023/01/23阅读:50主题:默认主题
nginx用return替代proxy_pass的写法
这几天遇到nginx配置proxy_pass对二级域名解析出的ip无效的问题,因为proxy_pass实际上都是转成ip再进行请求,所以就存在直接配置域名转发无效的问题,查找资料找到可以用return 307的方式来代替
if ($request_uri ~ ^/api/(.*)$ ){
return 307 https://xxx.xxx.com/$1;
}
上面代码的效果是把原请求中的api去除,并307临时重定向到https://xxx.xxx.com/,达到与下面代码
proxy_pass https://backend/;
proxy_pass一样的效果,这样就可以直接用域名而不怕proxy_pass解析成ip无法访问了,至于后续可能出现的跨域报错问题可以到后端配置处理下,这篇就不涉及了
贴出nginx完整配置如下
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
upstream backend {
server xxx.xxx.com
}
server {
listen 80;
server_name 0.0.0.0;
location / {
root /app;
index index.html;
try_files $uri $uri/ /index.html;
}
location /api/
{
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' '*';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' '*';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' '*';
}
# 原请求uri中带有的api的会被截取保存在$1,此处api已被去除,达到和proxy_pass https://backend/一样的效果
if ($request_uri ~ ^/api/(.*)$ ){
return 307 https://xxx.xxx.com/$1;
}
# proxy_pass https://backend/;
# 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 REMOTE-HOST $remote_addr;
# #缓存相关配置
# #proxy_cache cache_one;
# #proxy_cache_key $host$request_uri$is_args$args;
# #proxy_cache_valid 200 304 301 302 1h;
# #持久化连接相关配置
# proxy_connect_timeout 3000s;
# proxy_read_timeout 86400s;
# proxy_send_timeout 3000s;
# #proxy_http_version 1.1;
# #proxy_set_header Upgrade $http_upgrade;
# #proxy_set_header Connection "upgrade";
# add_header X-Cache $upstream_cache_status;
# #expires 12h;
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
作者介绍
f
fatelyh
V1