1. 下載、安裝、啓動
# 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配置到環境變量中。