【问题标题】:Rails API only configuration NGINXRails API 仅配置 NGINX
【发布时间】:2019-12-30 14:09:16
【问题描述】:

在 Amazon 上,Linux 使用 Rails 应用程序运行 Nginx。都好。 添加了 Rails API 应用程序(API 仅以 /api/v1/xxxxx 开头的路由)

API 的 Nginx 配置

upstream cb_api {
  server unix:///var/www/html/counterpoint-api/shared/sockets/puma.sock;
}

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

  root /var/www/html/counterpoint-api/public;
  index index.html index.htm;
  server_name cb-api.ariki.online;

  location ~ ^api/v1/(.+)$ {
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Host $http_host;
       proxy_pass http://cb_api;
       #proxy_redirect off;
  }


}

我尝试了所有我能想到的变体,但总是从 Nginx 收到 403 错误。

有人有有效的示例配置吗?

【问题讨论】:

    标签: ruby-on-rails nginx


    【解决方案1】:

    选项 1

    您可以在 ^api/v1/(.+)$ 上简单地重定向到端口 3000(rails 正在运行的地方)

    这是最简单的选择:

    server {
        listen 80;
        listen [::]:80;
    
        server_name cb-api.ariki.online;
    
        location ~ ^api/v1/(.+)$ {
            proxy_pass http://127.0.0.1:3000;
        }
    }
    

    然后,在 3000 端口中启动您的 rails 应用程序。

    选项 2

    在您的应用中创建配置文件:

    $ touch /home/your_linux_user/your_app_name/config/nginx.conf

    在您的配置文件中添加以下内容:

    $ sudo vim /home/your_linux_user/your_app_name/config/nginx.conf

    upstream puma {
      server unix:///home/your_linux_user/your_app_name/tmp/sockets/your_linux_user-puma.sock;
    }
    
    server {
      listen 80 default_server deferred;
      # server_name example.com;
    
      root /home/your_linux_user/your_app_name/public;
      access_log /home/your_linux_user/your_app_name/log/nginx.access.log;
      error_log /home/your_linux_user/your_app_name/log/nginx.error.log info;
    
      location ^~ /assets/ {
        gzip_static on;
        expires max;
        add_header Cache-Control public;
      }
    
      try_files $uri/index.html $uri @puma;
      location @puma {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
    
        proxy_pass http://puma;
      }
    
      error_page 500 502 503 504 /500.html;
      client_max_body_size 10M;
      keepalive_timeout 10;
    }
    

    然后创建一个指向您的 conf 的链接并启动 nginx:

    $ sudo rm /etc/nginx/sites-enabled/default

    $ sudo ln -nfs /home/your_linux_user/your_app_name/config/nginx.conf /etc/nginx/sites-enabled/your_app_name

    $ sudo service nginx 启动

    最后,运行 puma 创建套接字文件:

    $ puma -b unix:///home/your_linux_user/your_app_name/tmp/sockets/your_app_name-puma.sock

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多