网站nginx配置优化

时间:2021-03-28

首先来看laravel框架的部署配置

server {

	#端口
    listen 80;
    #域名
    server_name example.com;
    #代码路径
    root /srv/example.com/public;

	#添加头部
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

	#默认首页文件
    index index.php;

	#字符编码
    charset utf-8;

	#添加转发
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

	#处理favicon.ico、robots.txt请求
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

	#自定义404错误页面
    error_page 404 /index.php;

	#处理PHP文件
    location ~ .php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

	
    location ~ /.(?!well-known).* {
        deny all;
    }
}

参考链接:https://laravel.com/docs/8.x/deployment

网站http跳转https

例如:wyzda.com 跳转 https://www.wyzda.com

server {
    listen 80;
    server_name wyzda.com;
    return 301 https://www.wyzda.com$request_uri;
}

配置https访问

www.crt、www.key为申请证书发放的文件,一同放在与 nginx.conf 同级目录cert下,便于管理。

server {
    listen 443 ssl;
    server_name www.wyzda.com;
    ssl_certificate cert/www.crt;
    ssl_certificate_key cert/www.key;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;
    root /usr/share/nginx/html/wyzda/public;
    index index.html index.htm;

}

配置错误页面

以下为配置 404 500 502 503 504 状态码的错误页面为 /usr/share/nginx/html/wyzda/public/error.html

server {
    listen 80;
    server_name www.wyzda.com;
    root /usr/share/nginx/html/wyzda/public;


    error_page 404 500 502 503 504 /error.html;

}

还可以重新指定错误文件,50x.html 为文件名。

server {
    listen 80;
    server_name www.wyzda.com;
    root /usr/share/nginx/html/wyzda/public;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

配置PHP文件找不到的错误页面

添加 try_files $uri =404;

server {
    listen 80;
    server_name www.wyzda.com;
    root /usr/share/nginx/html/wyzda/public;


    error_page 404 500 502 503 504 /error.html;
    location ~ .php$ {
        try_files $uri =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

}

配置静态文件重定向

比如:图片请求cdn域名

server {
    listen 80;
    server_name wyzda.com;
    return 301 https://www.wyzda.com$request_uri;
}

以下配置在http节点上配置

开启gzip

gzip on;

隐藏nginx版本号

server_tokens off;

配置nginx文件上传大小

client_max_body_size 200m;