配置NGINX以服务SPA应用程序

时间:2018-12-02 09:32:13

标签: reactjs nginx

我是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。如何配置它?

1 个答案:

答案 0 :(得分:0)

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

看看我的设置:

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]
相关问题