nginx如何配置域名解析和文件站点,nginx常规操作, nginx资源路径无法定位,404

1.前言

记载了一些nginx常规操作

2.常见问题

记载了一些常见错误和解决方案

2.1资源路径错误,导致404.

  • 同一个servername,只能有一个root,换句话说,具备不同静态资源路径的项目,必须分不同的servername;
  • 解决方案,配置server的root:
server{
    listen 80;
    server_name xxx.xxx.com;
    access_log /data/nginx/log/xxx.access.log;
    error_log /data/nginx/log/xxx.error.log;
    root /x/x/x;
...
}

2.2 proxy_pass 多余前缀,导致定位不到后端服务

  • location /dev/ {proxy_path http://localhost:5555} ,将反向代理至 localhost:5555/dev,而不是localhost:5555
  • 解决方案,后端服务代码层,增加前缀/dev ,或者使用rewrite代替proxy_pass
    location /dev/ {
        rewrite ^/dev/(.*) /$1 break;
        proxy_pass http://localhost:5555;
    }

3.常规操作

记载了一些,可以拿来复制粘贴的常规操作

3.1文件站点

server {
    listen 80;
    server_name xxx.xxx.com;
    access_log /data/nginx/log/xxx.access.log;
    error_log /data/nginx/log/xxx.error.log;

    location / {
       proxy_pass http://127.0.0.1:8088;
       proxy_redirect off;
       proxy_set_header Host $host;
       proxy_set_header REMOTE_ADDR $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    location /xxxxxx.txt {
       return 200 '文件内容';
    }
}

3.2 https基本配置

doc.conf

# http 80
server {
    listen      80;
    server_name xxx.xxxx.com;
    root /home/fwhez/doc;

    # request header
    proxy_set_header   Host             $http_host;
    proxy_set_header   Cookie           $http_cookie;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-Proto    $scheme;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;

    location / {
        proxy_pass http://localhost:4001;
    }
}

# https 443
server {
    listen       443 ssl;
    server_name  xxxx.xxx.com;
    root         /usr/share/nginx/html;

    ssl_certificate "/etc/nginx/certs/xyx.crt";
    ssl_certificate_key "/etc/nginx/certs/xyx.key";
    ssl_session_cache shared:SSL:1m;
    ssl_session_timeout  10m;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # request header
    proxy_set_header   Host             $http_host;
    proxy_set_header   Cookie           $http_cookie;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-Proto    $scheme;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    location  / {
        proxy_pass http://localhost:4001;
    }

3.3 路径重写

    location /dev/ {
        rewrite ^/dev/(.*) /$1 break;
        proxy_pass http://localhost:5555;
    }

3.4 服务节点负载均衡

upstream srv {
    hash $remote_addr consistent;
    server localhost:8301;
    server localhost:8302;
}

location /dev/ {
    rewrite ^/dev/(.*) /$1 break;
    proxy_pass http://srv;
}

你可能感兴趣的:(nginx)