Nginx

nginx 配置和上游伺服器出現問題

  • August 5, 2015

我正在嘗試配置兩個由 nginx 提供的應用程序。第一個似乎工作正常,我為第二個複制了配置,但是我遇到了一些問題。

我正在執行一個由 Unicorn 支持的 Sinatra 伺服器,使用套接字傳遞上游資訊。我可以很好地到達根域(api.richardson.co.nz),一切似乎都正常,但是一旦我嘗試訪問根域之外的路徑(api.richardson.co.nz/games),我收到“未找到”錯誤。

這是我的 nginx 配置文件:

worker_processes 1;
user nginx web;
pid /tmp/nginx.pid;
error_log /var/www/knowyourgenre.com/shared/log/nginx.error.log;

events {
 worker_connections 1024; # increase if you have lots of clients
 accept_mutex off; # "on" if nginx worker_processes > 1
 use epoll; # enable for Linux 2.6+
}

http {
 include mime.types;
 default_type application/octet-stream;
 access_log /tmp/nginx.access.log combined;
 sendfile on;
 tcp_nopush on; # off may be better for *some* Comet/long-poll stuff
 tcp_nodelay off; # on may be better for some Comet/long-poll stuff
 gzip on;
 gzip_http_version 1.0;
 gzip_proxied any;
 gzip_min_length 500;
 gzip_disable "MSIE [1-6]\.";
 gzip_types text/plain text/html text/xml text/css
            text/comma-separated-values
            text/javascript application/x-javascript
            application/atom+xml;

 upstream app_server {
   server unix:/var/www/knowyourgenre.com/current/unicorn.sock fail_timeout=0;
   server localhost:8080 fail_timeout=0;
 }

 upstream api {
   server unix:/var/www/api/unicorn.sock fail_timeout=0;
   server localhost:8081 fail_timeout=0;
 }

 server {
   listen 80; # for Linux
   client_max_body_size 4G;
   server_name .knowyourgenre.com;
   keepalive_timeout 5;
   root /var/www/knowyourgenre.com/current/public/;
   try_files $uri/index.html $uri.html $uri @app;

   location @app {
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header Host $http_host;
     proxy_redirect off;
     proxy_pass http://app_server;
   }

   error_page 500 502 503 504 /500.html;
   location = /500.html {
     root /path/to/app/current/public;
   }
 }

 server {
   listen 80; # for Linux
   client_max_body_size 4G;
   server_name .richardson.co.nz;
   keepalive_timeout 5;
   root /var/www/api;
   try_files $uri/index.html $uri.html $uri @app;

   location @app {
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header Host $http_host;
     proxy_redirect off;
     proxy_pass http://api;
   }

   # Rails error pages
   error_page 500 502 503 504 /500.html;
   location = /500.html {
     root /path/to/app/current/public;
   }
 }

}

上游伺服器中的錯誤會導致返回“未找到”嗎?我很確定一切都在 Sinatra 伺服器中工作,但我可能錯過了一些東西。

在根值的末尾添加一個斜線。

root /var/www/api/;

另外,我建議將“try_files”包裝在一個位置。

location / {
   try_files $uri/index.html $uri.html $uri @app;
}

引用自:https://serverfault.com/questions/295736