reactjs - 配置 NGINX 以服务于 SPA 应用程序
问题描述
我是 Nginx 的初学者,所以我按照在线指南对其进行配置以服务于我的 React Web 应用程序。显然,在调试模式下,我的应用程序就像一个魅力。
我的测试服务器:
server {
listen 80;
root /var/www/my-app/build;
index index.html index.htm index.nginx-debian.html;
server_name XXX.XXX.XXX.XXX;
location / {
try_files $uri /index.html;
}}
部署后,当我尝试输入不同的路径(例如:XXX.XXX.XXX.XXX/home)时,它总是响应 404。如何配置它?
解决方案
您将需要一些重定向规则。
看看我的设置:
location / {
rewrite ^(.*)$ https://$http_host/$1 redirect;
if ($http_host ~* "^rickvanlieshout.com"){
rewrite ^(.*)$ http://www.rickvanlieshout.com/$1 redirect;
}
if ($http_host ~* "^mastermindzh.com"){
rewrite ^(.*)$ http://www.mastermindzh.com/$1 redirect;
}
if (!-e $request_filename){
rewrite ^(.*)$ /index.html break;
}
}
如果您的服务器支持,您也可以使用 .htaccess 执行此操作:
# Enable rewriting.
RewriteEngine on
# Optional: do not allow perusal of directories.
Options -Indexes
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301]
RewriteCond %{HTTP_HOST} ^rickvanlieshout.com [NC]
RewriteRule ^(.*)$ http://www.rickvanlieshout.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^mastermindzh.com [NC]
RewriteRule ^(.*)$ http://www.mastermindzh.com/$1 [L,R=301]
# Optional: explicitly enable per-directory rewrites in the .htaccess context.
Options +FollowSymLinks
# To be able to access existing directories and files (standalone scripts).
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# Redirect everything else to index.html.
# Add QSA to ensure that querystring variables are registered as such.
RewriteRule . index.html [L,QSA]
推荐阅读
- laravel - Bangla unicode 字体未在 mpdf 中显示
- azure-stream-analytics - 是否可以使用 azure 流分析基于给定的超时检测相关事件的缺失?
- php - 将数据保存到sql server时如何将符号'更改为`
- java - 违反了唯一约束 - 应该不可能,但仍然......为什么?
- vba - PL/SQL 数据库值未正确反映到 SSIS 脚本
- mysql - 如何将我的 Android 应用程序连接到存储在服务器中的 MySQL 数据库?
- go - 如何根据请求 URL 使用 golang GIN 路由 HTTP 请求
- angular - Rxjs:被困在返回一个参数数组
- react-native - 未定义不是函数(评估'object.getOwnPropertyDescriptors(arguments [i])')
- excel - 如何创建一个删除包含先前日期的行的循环