1. 安裝nginx
$ brew install nginx
nginx安裝路徑為,/usr/local/Cellar/nginx/1.12.2_1/bin/nginx
。
2. 啟動
$ nginx
3. 新建配置文件
nginx配置文件位于/usr/local/etc/nginx/
文件夾中,
其中,/usr/local/etc/nginx/nginx.conf
是主配置文件。
我們一般會將服務器對應不同網站的配置,
放到/usr/local/etc/nginx/servers/
文件夾中。
例如,新建/usr/local/etc/nginx/servers/test.conf
文件,
server {
# 監聽的端口號
listen 8081;
server_name localhost;
# localhost:8081/ 訪問的根目錄,必須寫絕對路徑
root /Users/thzt/Test/test-nginx/;
charset utf-8;
location / {
index index.html;
}
}
并在/Users/thzt/Test/test-nginx/
文件夾,添加index.html
。
4.重新加載配置
$ nginx -s reload
5. 瀏覽器訪問
使用瀏覽器打開,http://localhost:8081/
,
將展示出/Users/thzt/Test/test-nginx/index.html
文件的內容。
注:
nginx本身自帶web server的功能,
不需要再在/Users/thzt/Test/test-nginx/
目錄下啟動一個web server。
6. rewrite
修改/usr/local/etc/nginx/servers/test.conf
配置文件,
server {
listen 8081;
# 不mock manage首屏展示
location ^~ /manage/index.html {
proxy_pass http://127.0.0.1:7001;
}
# 不mock manage頁面發送的請求
location ^~ /demo/ {
proxy_pass http://127.0.0.1:7001;
}
# 將8081端口的“/mock/page/”請求,轉發到7001端口
# 自動攜帶原請求的查詢參數
location ^~ /mock/page/ {
proxy_pass http://127.0.0.1:7001;
}
# 語法:rewrite 規則 定向路徑 重寫類型 ;
# 將http://localhost:8081/xxx.json的請求,
# 轉發到http://127.0.0.1:7001/mock/ajax/?url=xxx.json
location ~* \.json$ {
rewrite (/.*\.json)$ http://127.0.0.1:7001/mock/ajax/?url=$1 redirect;
}
}
7. log地址
/usr/local/var/log/nginx/error.log