Skip to content

Nginx

介绍

Nginx 是一个高性能的开源 Web 服务器和反向代理服务器,以其稳定性、丰富的功能集和低资源消耗。

安装

shell
# 安装 nginx
sudo apt update
sudo apt install nginx

# 查看 nginx 安装路径
which nginx

# 检查是否配置正确
sudo nginx -t

# 删除
sudo apt-get --purge remove nginx
sudo apt-get autoremove
# 查看Nginx系统模块,已安装的全部卸载
dpkg --get-selections|grep nginx
sudo apt-get --purge remove nginx-common
sudo apt-get --purge remove nginx-core
dpkg --get-selections|grep nginx
sudo apt-get install nginx

# 自动移除全部不使用的软件包
sudo apt-get autoremove

# 重启 nginx
nginx -s reload
sudo /etc/init.d/apache2 stop # 如果重启失败了先执行这个先关闭 apache2
sudo systemctl start apache2 # 重新启动 apache2

配置文件

nginx 默认配置文件在 /etc/nginx,可以在 sites-enabled 目录下新增配置文件

下面是我的服务器反向代理配置文件,并且设置了图片缓存相应头,凡是 /image | /uploads 的图片都会执行被缓存到浏览器中

conf
server {
    listen 80;
    server_name abbbbbbbbcd.com;

    # Redirect HTTP to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name abbbbbbbbcd.com;

    # SSL configuration
    ssl_certificate /home/project/xxxxxx/ssl/abbbbbbbbcd.com.pem;
    ssl_certificate_key /home/project/xxxxxx/ssl/abbbbbbbbcd.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;

    location ~ ^/(images|uploads) {
        expires 30d;  # 设置缓存过期时间为 30 天
        add_header Cache-Control "public";  # 指示响应可以被任何缓存缓存
        add_header Last-Modified $date_gmt;  # 添加响应的最后修改时间

        proxy_pass http://localhost:1219;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location / {
        proxy_pass http://localhost:1219;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

检查配置文件

修改玩配置文件之后需要检查配置是否正确,使用下面命令

shell
nginx -t

如果打印下面内容则代表配置成功

shell
nginx: configuration file /etc/nginx/nginx.conf test is successful
root@hcss-ecs-7f6c:~# sudo service nginx reload

如果配置成功之后需要重启 nginx 服务,下面命令可以重启服务,如果没有打印任何日志说明重启成功

shell
sudo service nginx reload