Virtual Host config for Nginx as Proxy

December 2, 2017 6.7k views
Nginx

I'm having a problem with Virtual Host on nginx as proxy for ubuntu. My website is been redirected from example.com to www.example.com/index.php
Also, my htaccess is not working. Someone could help me? Thanks.

server {
    listen 80;
    server_name test.io www.test.io;
    root /var/www/test.io;
    index index.php index.htm index.html;

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        proxy_pass http://your_ip_address:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~ /\. {
        deny all;
    }
}
1 Answer

Without some additional context, it's difficult to answer your question. It looks like you are trying to use Nginx as a reverse proxy in front of Apache. Is that correct?

The reason for the redirects to index.php is your try_files directive. The last entry on that line is a fallback. So if $uri or $uri/ are not exact matches, Nginx will redirect the request to /index.php This can be useful for some PHP applications like WordPress where the index.php file is the main entrypoint for the app, including for things like error pages. Find out more about how Nginx routes requests in this tutorial:

Your configuration also only proxies requests to PHP files. If you'd like all requests to be passed through to Apache on port 8080, you could simplify the Nginx config to something like:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://your_server_ip:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

For an in-depth look at how to configure Nginx as a reverse proxy for Apache, check out:

by Justin Ellingwood
Nginx is one of the most popular web servers in the world. In this guide, we will discuss how Nginx selects the server and location block that will handle a given client's request. We will go over the algorithm in place, as well as the directives and options you can use to modify the selection process.
Have another answer? Share your knowledge.