您的位置:首页 > 运维架构 > Nginx

Nginx服务器实现跨域转发(windows)

2017-12-21 00:00 357 查看
摘要: 作为web开发者,前后端分离经常会碰到跨域的问题,除了jsonp,后台设置,跨域转发插件之外,也可以本地搭建一个Nginx服务器,实现跨域转发,反向代理。

1. 下载、安装、启动

地址:https://nginx.org/en/download.html

解压

在解压后的目录,同时按住Shift键和鼠标右键,点击[在此处打开命令窗口]

输入start nginx,回车。然后在地址栏输入localhost回车,应该有wellcom nginx的字样。

# nginx命令
start nginx  #开启Nginx服务
nginx -s stop    #关闭Nginx服务
nginx -s reload    #重启Nginx服务

2.完成跨域转发配置

Nginx主要配置文件为conf目录下的nginx.conf文件,先介绍下主要配置项。

server {
listen  80;    # 监听的本地端口,默认为80
server_name localhost;    #本地服务的名字,默认为localhost或127.0.0.1

location / {
root   E:/nginx;    # 服务的根目录
index  index.html index.htm;    # 服务默认启动的主文件,可以写多个(如果根目录没有的话,容易报403错误)
}

location ~ /api/ {    #匹配所有以api开头的请求,然后转发
proxy_pass  http://chinahufei.com/api;        # 跨域转发到http://chinahufei.com/api
proxy_set_header Host $host:80;                # 请求的主机名
proxy_set_header X-Real-IP $remote_addr;    #请求的真实IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    # 表示请求发起源
}
}

3.完成静态代码在本地访问,接口访问远端

server {
listen       80;
server_name  localhost;

#charset koi8-r;

#access_log  logs/host.access.log  main;

location / {
root   E:/nginx;    # 文件根目录
index  index.html index.htm;
}
location ~ /goods/ {
proxy_pass  http://chinahufei.com;      # 转发地址和端口
proxy_set_header Host $host:80;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#error_page  404              /404.html;
# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}
}

4.如果需要更方便的话,可以把Nginx配置到环境变量中。

具体的可以这篇博客:https://my.oschina.net/chinahufei/blog/1577803
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息