How to fix 403 Fobidden issue on Nginx + Rails application
I have been setting up many servers for several clients using the combination of Nginx + Passenger or Nginx + Unicorn. And one of the most common issues I see when installing and configuring Nginx is 403 Forbidden error. And in this post, I am going to point out several reasons and solution with hope that you can save your day
First reason: Your Passenger location is incorrect
In your nginx.conf file, you will perhaps see the following line
passenger_root ...
passenger_ruby ...
Please make sure that you are using correct path to passenger and ruby on your server. For example, I have RVM installed on my server and my Ruby path will look like this:
passenger_ruby /home/deploy/.rvm/wrappers/ruby-1.9.3-p547/ruby;
And you can look for passenger_root by running the following command on server:
passenger-config --root
Second reason: Permission on project folder is incorrect
You need to add Execute permission on your project folder on server to make sure Nginx can access and serve the project to clients. The following command might be helpful
sudo chmod a+x <path/to/project/folder>
Third reason: Redundant location /
section in Nginx config file
I was spending whole day because of this issue because it would often be forgotten when doing configuration. So, please make sure to remove this location /
section inside your virtual host definition. Here is an example of working Nginx configuration which you might want to use:
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
server_name www.iconicdev.info;
passenger_enabled on;
rails_env production;
root /home/deploy/test/current/public;
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ~* ^/assets/ {
expires 1y;
add_header Cache-Control public;
add_header Last-Modified "";
add_header ETag "";
break;
}
}
If you have seen similar error but found a different solution, please let me know and I will update this to make sure we can help other friends