nginx server_name 多个的话;空格隔开
server_name baidu.com baidu.me;
如果很多的话也可以用正则;我的需求;xxx-api-dev.zzg.me 统一跳转到127.0.0.1:8888
server { listen 80; server_name ~^.;-api-dev.zzg.me$; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://127.0.0.1:8888; }
加一条默认的阻挡。
当所有server的规则都不匹配时;nginx会采用第一条server配置;所以一般第一条server会使用阻止页面。
server { listen 80 default_server; server_name _; return 404; }
另外可以直接拦截OPTIONS请求;返回204;减轻真实服务器的性能消耗
location / { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods ;GET, POST, OPTIONS;; add_header Access-Control-Allow-Headers ;DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization;; if ($request_method = ;OPTIONS;) { return 204; } proxy_pass http://127.0.0.1:8080; proxy_set_header X_Real_IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; }
或者
if ($request_method = ;OPTIONS;) { add_header ;Access-Control-Allow-Origin; ;$http_origin; always; add_header ;Access-Control-Allow-Methods; ;GET, POST, PUT, DELETE, OPTIONS; always; add_header ;Access-Control-Allow-Headers; ;Accept, Authorization, Cache-Control, Content-Type, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Requested-With, Token, x-access-token; always; # Tell client that this pre-flight info is valid for 20 days add_header ;Access-Control-Max-Age; 1728000; add_header ;Content-Type; ;text/plain charset=utf-8;; add_header ;Content-Length; 0; return 204; }
Nginx中server_name 参数详解