首页 > 解决方案 > 配置 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。如何配置它?

标签: reactjsnginx

解决方案


您将需要一些重定向规则。

看看我的设置:

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]

推荐阅读