温馨提示×

centos如何配置nginx实现动静分离

小樊
93
2025-02-13 08:05:46
栏目: 智能运维
Centos服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在CentOS上配置Nginx实现动静分离,通常涉及以下几个步骤:

1. 安装Nginx

首先,确保你已经安装了Nginx。如果没有安装,可以使用以下命令进行安装:

sudo yum install epel-release
sudo yum install nginx

2. 配置Nginx

编辑Nginx的配置文件,通常位于 /etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf

示例配置

假设你有一个静态网站目录 /var/www/html/static 和一个动态网站目录 /var/www/html/dynamic

server {
    listen 80;
    server_name example.com;

    # 静态文件处理
    location /static/ {
        root /var/www/html;
        expires 30d;
        add_header Cache-Control "public";
    }

    # 动态内容处理
    location / {
        proxy_pass http://backend_server;
        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 /static/ 块用于处理静态文件请求。
  • location / 块用于将动态内容请求转发到后端服务器(例如,使用 proxy_pass 指令)。

3. 启动和测试Nginx

启动Nginx并检查其状态:

sudo systemctl start nginx
sudo systemctl status nginx

确保没有错误信息,并且Nginx正在运行。

4. 测试配置

打开浏览器并访问你的服务器地址(例如 http://example.com),你应该能够看到静态文件和动态内容分别被正确处理。

5. 调整防火墙设置

如果你的服务器启用了防火墙,确保允许HTTP(端口80)和HTTPS(端口443)流量:

sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

6. 可选:配置SSL/TLS

如果你需要为你的网站配置SSL/TLS,可以使用Let’s Encrypt免费证书:

sudo yum install certbot python2-certbot-nginx
sudo certbot --nginx -d example.com

按照提示完成证书的申请和配置。

通过以上步骤,你就可以在CentOS上配置Nginx实现动静分离了。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:CentOS Nginx如何实现动静分离

0