在Ubuntu上使用Nginx实现动静分离,可以通过配置Nginx来区分处理静态文件和动态请求。以下是一个基本的步骤指南:
首先,确保你已经安装了Nginx。如果没有安装,可以使用以下命令进行安装:
sudo apt update
sudo apt install nginx
编辑Nginx的配置文件,通常位于 /etc/nginx/nginx.conf
或 /etc/nginx/sites-available/default
。你可以创建一个新的配置文件或修改现有的配置文件。
假设你有一个静态文件目录 /var/www/static
和一个动态应用目录 /var/www/dynamic
,你可以这样配置:
server {
listen 80;
server_name example.com;
# 静态文件处理
location /static/ {
alias /var/www/static/;
expires 30d;
add_header Cache-Control "public";
}
# 动态内容处理
location / {
proxy_pass http://localhost:8000; # 假设你的动态应用运行在8000端口
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/
:这个块处理所有以 /static/
开头的请求,并将它们代理到 /var/www/static/
目录。expires
和 add_header
指令用于设置缓存头,以便浏览器可以缓存静态文件。location /
:这个块处理所有其他请求,并将它们代理到运行在 localhost:8000
的动态应用。在保存配置文件后,测试Nginx配置是否正确:
sudo nginx -t
如果配置没有问题,你会看到类似以下的输出:
nginx: configuration file /etc/nginx/nginx.conf test is successful
最后,重新加载Nginx以应用新的配置:
sudo systemctl reload nginx
打开浏览器并访问 http://example.com/static/yourfile.jpg
和 http://example.com/dynamic/route
,确保静态文件和动态内容都能正确显示。
通过以上步骤,你就可以在Ubuntu上使用Nginx实现动静分离了。