nginx处理跨域
因为浏览器的同源策略,导致在a站点拿不到b站点的资源,然而前后端分离开发,前端开起的服务和后端起的服务IP地址不同,导致拿不到资源,这时就需要做代理解决跨域问题
nginx的默认配置是这样:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
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;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 这句指最终配置加载conf.d下面的所有配置文件
include /etc/nginx/conf.d/*.conf;
# 这里是配置代理的地方
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
如要配置需要代理的地址http://192.168.11.20:8082/api/getdata,可如下配置:
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location /api/ {
proxy_pass http://192.168.11.20:8082/;
}
}
若本身后端服务配置的接口地址已经是api,则需要改成其他的名字:
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location /api/ {
proxy_pass http://10.33.29.63:8802/;
}
location /otherApi/ {
proxy_pass http://192.168.11.20:8082/api/;
}
}