nginx 配置模板

http 跳转 https

server {
    listen 80;
    server_name  domain;

    return 301   https://$host$request_uri;
    #rewrite ^(.*)$  https://$host$1 permanent;
}

整合 php-fpm

server {
    listen 80;
    #listen          [::]:80;
    server_name  domain;

    root   /home/www/public;
    index  index.html index.htm index.php;

    # 请求 body 大小
    client_max_body_size   20m;

    location / {
        #autoindex on;
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        # fastcgi_pass 二选一
        fastcgi_pass 127.0.0.1:9000;
        #fastcgi_pass   unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        # 环境参数
        fastcgi_param APP_ENV production;
        include fastcgi_params;
    }
}

https 配置

server {
    listen 443 ssl;
    server_name  domain;

    ssl on;

    ssl_certificate      /etc/nginx/cert/ssl.pem;
    ssl_certificate_key  /etc/nginx/cert/ssl.key;

    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers  ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_prefer_server_ciphers  on;
}

启用 gzip 压缩传输

server {
    gzip              on;
    gzip_min_length   1k;
    gzip_buffers      4 16k;
    gzip_http_version 1.1;
    gzip_comp_level   6;
    gzip_types        text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php application/javascript application/json;
    gzip_types        text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_disable      "MSIE [1-6]\.";
    gzip_vary         on;
}

反向代理

server {
    location / {
        proxy_pass http://127.0.0.1:8081/$1$is_args$args;
    }

    location ~* ^/api/(.*) {
        proxy_pass http://127.0.0.1:8082/$1$is_args$args;

        # CORS
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' *;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD';
            # 允许添加更多自定义 header
            add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With,token';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }
    }
}

日志、异常等其他配置

server {
    access_log  /var/log/nginx/access.log main;
    error_log   /var/log/nginx/error.log;

    error_page  404        /404.html;
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    location ~ /\.ht {
        deny  all;
    }
}