nginx 命令

重启 nginx

  1. nginx -s reload

nginx 配置

配置资源查找路径

http://nginx.org/en/docs/http/ngx_http_core_module.html#root
http://nginx.org/en/docs/http/ngx_http_core_module.html#alias

  1. location /i/ {
  2. root /data/w3/images/;
  3. }
  4. # 请求 /i/test.jpg , 查找资源的路径为 /data/w3/images/i/test.jpg
  1. location /i/ {
  2. alias /data/w3/images/;
  3. }
  4. # 请求 /i/test.jpg , 查找资源的路径为 /data/w3/images/test.jpg

rootalias字段的区别是alias配置的是路径别名,不会带上匹配的前缀。且二者的使用范围不同。root可以使用在 http、server、location 中,但 alias只能使用在 location 中。

配置首页

http://nginx.org/en/docs/http/ngx_http_index_module.html

  1. location / {
  2. index index.html index.htm;
  3. }

配置文件查找顺序

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
当匹配一个 location 时,可以设置匹配到的资源的查找顺序,从而可以设置一个查找不到时的默认返回值。

  1. location / {
  2. root /data/w3/;
  3. try_files $uri $uri/ /index.html;
  4. }
  5. # 请求 /test 的时候先找 /data/w3/test 资源,再找 /data/w3/test/ 文件夹。都找不到时,
  6. # 就重新请求 /index.html。
  7. location /i/ {
  8. root /data/w3/;
  9. try_files $uri $uri/ /i/index.html;
  10. }
  11. # 请求 /i/test 的时候先找 /data/w3/i/test 资源,再找 /data/w3/i/test/ 文件夹。都找不到时,
  12. # 就重新请求 /i/index.html。

try_files 里的 $uri 变量就是 location 匹配的路径值。
这种配置常常用于 history路由模式。
HTML5 History 模式 | Vue Router

配置代理

http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

  1. location /test-proxy {
  2. proxy_pass http://xxx.xx.x
  3. }
  4. # 访问 /test-proxy 路径,都会被转发到 proxy_pass 指定的服务器