linux如何部署前端react项目
安装Node.js环境
确保系统已安装Node.js(建议使用LTS版本),可通过以下命令检查版本:
node -v
npm -v
若未安装,可通过官方二进制包或工具如nvm安装:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash
nvm install --lts
构建React项目
进入项目目录,安装依赖并执行构建(生成静态文件):
cd /path/to/react-project
npm install
npm run build
构建完成后,静态文件默认生成在build/目录(Create React App项目)或dist/目录(Vite等工具)。

配置Web服务器
使用Nginx
- 安装Nginx:
sudo apt update && sudo apt install nginx # Debian/Ubuntu sudo yum install nginx # CentOS/RHEL - 修改Nginx配置,指向构建目录:
server { listen 80; server_name your-domain.com; root /path/to/react-project/build; index index.html; location / { try_files $uri $uri/ /index.html; } } - 重启Nginx生效:
sudo systemctl restart nginx
使用Apache
- 安装Apache:
sudo apt install apache2 # Debian/Ubuntu sudo yum install httpd # CentOS/RHEL - 配置虚拟主机,启用
mod_rewrite:<VirtualHost *:80> ServerName your-domain.com DocumentRoot /path/to/react-project/build <Directory "/path/to/react-project/build"> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </Directory> </VirtualHost> - 重启Apache:
sudo systemctl restart apache2
配置HTTPS(可选)
使用Let's Encrypt免费证书:
- 安装Certbot:
sudo apt install certbot python3-certbot-nginx # Nginx sudo apt install certbot python3-certbot-apache # Apache - 获取证书:
sudo certbot --nginx -d your-domain.com - 自动续期:
sudo certbot renew --dry-run
进程管理(可选)
使用PM2管理Node.js服务(若需服务端渲染):
- 全局安装PM2:
npm install -g pm2 - 启动服务:
pm2 start npm --name "react-app" -- start - 设置开机自启:
pm2 startup pm2 save






