在CentOS系统下,使用Nginx实现动静分离主要涉及到配置Nginx的location块,将静态资源请求和动态请求分别处理。以下是一个基本的步骤指南:
首先,确保你已经安装了Nginx。如果没有安装,可以使用以下命令进行安装:
sudo yum install epel-release
sudo yum install nginx
编辑Nginx的配置文件,通常位于/etc/nginx/nginx.conf
或/etc/nginx/conf.d/default.conf
。
确保你的Nginx配置文件中包含以下基本配置:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
假设你的静态资源(如CSS、JS、图片等)存放在/var/www/static
目录下,你可以这样配置:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
location /static/ {
alias /var/www/static/;
expires 30d;
add_header Cache-Control "public";
}
location / {
try_files $uri $uri/ =404;
}
}
假设你的动态请求需要通过PHP-FPM处理,你可以这样配置:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location /static/ {
alias /var/www/static/;
expires 30d;
add_header Cache-Control "public";
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location / {
try_files $uri $uri/ =404;
}
}
保存配置文件后,重启Nginx以应用更改:
sudo systemctl restart nginx
打开浏览器,访问你的服务器地址,确保静态资源能够正确加载,并且动态请求能够通过PHP-FPM处理。
通过上述步骤,你可以在CentOS系统下使用Nginx实现动静分离。静态资源通过location /static/
块处理,动态请求通过location ~ \.php$
块处理。这样可以提高网站的性能和安全性。