最近公司打算採用先後端分離的開發模式,這就意味着先後端代碼將分爲兩個工程了,因此我打算用nginx的反向代理來搭建一個開發環境,方便後續的開發。html
第一步固然是安裝nginx,這裏我是直接用windows下的一個第三方包管理器scoop
來安裝,過程很簡單,一個命令就夠了:前端
scoop install nginx
而後,咱們須要在nginx中配置咱們的項目,參考nginx的相關配置,直接貼配置(主要是兩個server的配置):nginx
#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include 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 logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; # 靜態頁面配置 server { listen 80; server_name static.mysite.com; location / { root C:/nginx/html/sysmgr; index index.html index.htm; } #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 C:/nginx/html/sysmgr; } } # 接口配置 server { listen 80; server_name api.mysite.com; # 容許來自靜態頁面的跨域請求 add_header Access-Control-Allow-Origin 'http://static.mysite.com' always; add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS' always; 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' always; if ($request_method = 'OPTIONS') { return 204; } location / { proxy_pass http://127.0.0.1:8080; index index.html index.htm; } } }
因爲我是我把前端代碼和後端程序都放在本地,因此須要在host中配置相關的地址:windows
127.0.0.1 static.mysite.com 127.0.0.1 api.mysite.com
.\nginx.exe -c .\conf\nginx.conf
而後,就能夠經過http://static.mysite.com
來訪問咱們的環境了。後端