本文简单记录一下常用的一些 Nginx 配置。

  • 安装 Ningx
  • 简单代理
  • 重写路径
  • nginxconfig: ⚙️ NGiИX config generator generator on steroids 💉

安装 Nginx

Brew 安装:

  • /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 安装 brew

  • brew install nginx 安装 nginx

从 Nginx 源码安装:

Nginx 命令 (Mac)

  • nginx to start nginx
  • nginx -s stop to stop nginx
  • nginx -s reload to reload config file
  • vi /usr/local/etc/nginx/nginx.conf to edit config file (default port 8080)
    • code /usr/local/etc/nginx/nginx.conf use vscode to edit

代理其他已有域名页面

location =/apple-app-site-association {
    proxy_pass  https://xxx.example.com/the/other/domain/file.json;
    proxy_set_header Host xxx.example.com;
}

重写路径代理

location ~ ^/path/(.*)$ {
    rewrite ^/path/(.*)$ /new/path/$1 break;
    proxy_pass http://xxx.example.com;
    proxy_set_header Host xxx.example.com;
}

Debug Nginx

https://coderwall.com/p/nmgwnw/debugging-nginx-rewrite

error_log  /Users/zhoukeke/error.log  notice;


http {
    ...others...
    
    rewrite_log on;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"'
                     ' UPSTREAM: $upstream_addr - $upstream_response_time - $request_time'
                     ' PROXY: $proxy_host - $proxy_port';

    access_log  /Users/zhoukeke/access.log  main;

	...others...
	
	# Example
	 # http://localhost:8080/httpbin/get
     location ~ ^/httpbin/(.*)$ {
         rewrite ^/httpbin/(.*)$ /$1 break;
         proxy_pass http://httpbin.org;
         proxy_set_header Host httpbin.org;
     }

Test it!

➜  curl -i http://localhost:8080/httpbin/get
HTTP/1.1 200 OK
Server: nginx/1.15.5
Date: Tue, 06 Nov 2018 15:38:30 GMT
Content-Type: application/json
Content-Length: 214
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Via: 1.1 vegur

{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Connection": "close",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.54.0"
  },
  "origin": "60.186.107.23",
  "url": "http://httpbin.org/get"
}

error.log

2018/11/06 23:38:30 [notice] 29229#0: *95 "^/httpbin/(.*)$" matches "/httpbin/get", client: 127.0.0.1, server: localhost, request: "GET /httpbin/get HTTP/1.1", host: "localhost:8080"
2018/11/06 23:38:30 [notice] 29229#0: *95 rewritten data: "/get", args: "", client: 127.0.0.1, server: localhost, request: "GET /httpbin/get HTTP/1.1", host: "localhost:8080"

access.log

127.0.0.1 - - [06/Nov/2018:23:38:30 +0800] "GET /httpbin/get HTTP/1.1" 200 214 "-" "curl/7.54.0" "-" UPSTREAM: 54.152.208.69:80 - 0.699 - 0.699 PROXY: httpbin.org - 80

References