本教程将详细介绍如何使用Nginx作为Web服务器来部署前端项目。Nginx是一个高性能的HTTP和反向代理服务器,以其稳定性、丰富的功能集、简单的配置和低资源消耗而闻名。
通过学习本教程,您将掌握从Nginx安装配置到前端项目部署的完整流程,包括HTTPS配置、性能优化、缓存设置等高级技巧。
本教程适合有一定Linux基础的前端开发人员,所有操作均在Ubuntu 20.04 LTS环境下测试通过。
sudo apt update
sudo apt install nginx
更新软件包列表并安装Nginx服务器。
sudo mkdir -p /var/www/your_project
sudo chown -R $USER:$USER /var/www/your_project
创建项目目录并设置权限。
sudo nano /etc/nginx/sites-available/your_project
创建Nginx配置文件。
sudo ln -s /etc/nginx/sites-available/your_project /etc/nginx/sites-enabled/
创建符号链接启用配置。
sudo nginx -t
sudo systemctl restart nginx
测试配置并重启Nginx。
npm run build
cp -r dist/* /var/www/your_project/
构建项目并复制到部署目录。
server {
listen 80;
server_name your_domain.com www.your_domain.com;
root /var/www/your_project;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /api {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
}
}
server {
listen 443 ssl;
server_name your_domain.com www.your_domain.com;
ssl_certificate /etc/letsencrypt/live/your_domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your_domain.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:...;
root /var/www/your_project;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
server {
listen 80;
server_name your_domain.com www.your_domain.com;
return 301 https://$host$request_uri;
}
使用Let's Encrypt可以免费获取SSL证书,运行sudo certbot --nginx -d your_domain.com -d www.your_domain.com自动配置HTTPS。
当访问网站时出现403 Forbidden错误,通常是由于权限问题导致的。
使用前端路由框架(如React Router, Vue Router)时,刷新页面出现404错误。
location / {
try_files $uri $uri/ /index.html;
}
在Nginx配置中添加上述代码,将所有路由请求重定向到index.html。
页面可以打开,但CSS、JS或图片等静态资源无法加载。