本地開發環境配置Nginx
目的:前端本地開發環境聯調測試服務器上的後端,Cookie不能跨域問題
Mac系統
- 1.安裝Nginx:
brew install nginx
安裝目錄:/usr/local/Cellar/nginx/
配置文件路徑:/usr/local/etc/nginx
日誌位置:
/usr/local/var/log/nginx/access.log
/usr/local/var/log/nginx/error.log
2. 查看Nginx配置文件:/usr/local/etc/nginx/
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 8080;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
include /usr/local/etc/nginx/conf.d/*.conf;
}
3. 在/usr/local/etc/nginx/conf.d/目錄下新建一個配置文件kdrp.conf:
觀察上面include的目錄,有的可能不是conf.d, 是servers目錄
server {
listen 80;
server_name localhost;
charset utf-8;
client_max_body_size 75M;
location ^~ /api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://***.com/api/;
}
location / {
proxy_pass http://localhost:8000/;
}
}
以/api/開頭的請求地址會轉發到測試服務器上 http://*.com/api/
其他請求地址會轉發到前端開發環境:http://localhost:8000/ (你需先啓動前端服務)
4. 測試Nginx配置文件是否正確:
> nginx -t
5. 啓動或重啓Nginx服務:
> nginx
或
> nginx -s reload
6.瀏覽器中輸入http://127.0.0.1/ 訪問
Windows系統
1. 下載nginx
2. 在nginx安裝目錄的conf目錄下新建一個配置文件kdrp.conf:
worker_processes 1;
error_log logs/error-debug.log info;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost 127.0.0.1 ;
charset utf-8;
client_max_body_size 75M;
location ^~ /api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://***.com/api/;
}
location / {
proxy_pass http://localhost:8000/;
}
}
}
3. 啓動Nginx服務:
先進入nginx安裝目錄(或自己配置環境變量)
nginx -c conf\kdrp.conf
4. 停止Nginx服務:
nginx -s stop
或
taskkill /F /IM nginx.exe > nul