【问题标题】:Nginx serve Rails route as default pageNginx 将 Rails 路由作为默认页面
【发布时间】:2020-04-30 08:54:44
【问题描述】:

我正在尝试为默认 Nginx 页面提供特定的 Rails 路由。 我有一个允许用户创建站点的应用程序,但该站点仅在某些条件下可用,因此在满足这些条件之前,不会创建该站点的 Nginx 服务器块,这意味着如果他们尝试使用他们的域访问他们的站点他们最终会看到 Nginx 默认页面(欢迎使用 Nginx)。

我想做的是让 Nginx 为 Rails 路由之一提供服务,使其对用户更加友好,并避免为那些不阅读说明的人(基本上是所有说明)提供不必要的支持问题。

我一直在默认 Nginx 配置文件中尝试不同的配置,但无济于事,Nginx 总是以服务于 Rails 应用程序的根页面而不是我想要的特定路径(/几乎在那里)结束:

/etc/nginx/sites-available/default

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/railsapp/public;

    passenger_enabled on;
    rails_env production;

    index almost-there.html;

    server_name _;

    location / {
        index almost-there.html;
    }
}

请注意,almost-there.html 是 rails 路由,而不是实际的静态 html 文件。

【问题讨论】:

    标签: ruby-on-rails nginx


    【解决方案1】:

    我不使用此框架,但您可能需要将访问者重定向到 /almost-there.html,但照常提供 /index.html

    例如:

    index index.html;
    
    location = / {
        return 302 /almost-there.html;
    }
    location / {
        try_files $uri $uri/ /index.html; 
    }
    

    或者,重定向所有路由:

    index index.html;
    
    location / {
        try_files $uri $uri/ @redirect;
    }
    location @redirect {
        rewrite ^/almost-there\.html$ /index.html last;
        return 302 /almost-there.html;
    }
    

    【讨论】:

      【解决方案2】:

      所以我最终做的是完全删除 location 块,以及 index 指令,而是将 / 重定向到我想要显示的 Rails 路由:

      rewrite ^/$ /almost-there redirect;
      

      需要注意的是,这是一种临时重定向,而不是永久重定向,因为我们不希望浏览器缓存此重定向以避免在准备好显示真实站点后出现问题。

      【讨论】:

        猜你喜欢
        • 2015-05-16
        • 2019-01-20
        • 2015-01-02
        • 2021-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多