react如何部署linux
部署 React 应用到 Linux 服务器的步骤
构建生产环境代码
在本地开发环境中运行构建命令,生成优化后的静态文件:
npm run build
这会生成一个 build 文件夹,包含所有压缩后的 HTML、CSS 和 JavaScript 文件。
传输文件到 Linux 服务器
使用 scp 或 SFTP 工具将 build 文件夹上传到服务器。例如:
scp -r build/ user@your_server_ip:/path/to/target/directory
配置 Web 服务器
根据使用的 Web 服务器选择对应配置:

Nginx 配置示例
在 /etc/nginx/sites-available/your_domain 中添加以下内容:
server {
listen 80;
server_name your_domain.com;
root /path/to/build;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
启用配置并重启 Nginx:
sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled
sudo systemctl restart nginx
Apache 配置示例
在 /etc/apache2/sites-available/your_domain.conf 中添加:

<VirtualHost *:80>
ServerName your_domain.com
DocumentRoot /path/to/build
<Directory /path/to/build>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
启用配置并重启 Apache:
sudo a2ensite your_domain.conf
sudo systemctl restart apache2
配置 HTTPS(可选)
使用 Certbot 获取免费 SSL 证书:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your_domain.com
设置防火墙
允许 HTTP/HTTPS 流量通过:
sudo ufw allow 'Nginx Full'
验证部署
访问服务器 IP 或域名,检查 React 应用是否正常加载。通过开发者工具查看是否有资源加载错误。






