Tutorial

How To Configure Nginx as a Reverse Proxy for Apache

How To Configure Nginx as a Reverse Proxy for Apache

This tutorial is out of date and no longer maintained.

Note: This tutorial is out of date and unmaintained. Updated versions are available for Ubuntu 18.04 and Ubuntu 16.04

Why Run Nginx and Apache Together

Both nginx and apache are powerful and effective servers. Apache currently reigns as the #1 server for websites and since its public release in 2006, nginx has taken the world by storm and is now the #2 server for active sites. The reasons for each respective server’s popularity are clear: apache’s power and nginx’s speed are well known. However, both servers do have drawbacks—apache is hard on server memory, while nginx (great at static files) needs the help of php-fpm or similar modules for dynamic content.

However, one can combine the two web servers to great effect, with nginx as static web server front and apache processing the back end.

Setup

To perform the steps in this tutorial, you will need to have sudo privileges on your virtual private server.

To create a user with sudo privileges, go through the third and fourth steps of the initial ubuntu server setup tutorial

Install nginx

To start off, we need to install and configure nginx which will serve the front end of our site.

Let’s download it from apt-get:

sudo apt-get install nginx

Once it has downloaded, you can go ahead and configure the virtual host to run on the front end.

There are a few changes we need to make in the configuration.

Configure nginx

Open up the nginx configuration.

sudo nano /etc/nginx/sites-available/example

The following configuration will set you up to use nginx as the front end server. It is very similar to the default set up, and the details are under the configuration.

server {
        listen   80; 

        root /var/www/; 
        index index.php index.html index.htm;

        server_name example.com; 

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

        location ~ \.php$ {
        
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8080;

         }

         location ~ /\.ht {
                deny all;
        }
}

The following changes were implemented in the configuration:

  • The root was set to the correct web directory
  • index.php was added on the index line
  • try_files attempts to serve whatever page the visitor requests. If nginx is unable, then the file is passed to the proxy
  • proxy_pass lets nginx the address of the proxied server
  • Finally the "location ~ /\.ht {" location block denies access to .htaccess files, if Apache's document root concurs with nginx's one

This configuration sets up a system where all extensions with a php ending are rerouted to the apache backend which will run on port 8080.

Activate the virtual host.

sudo ln -s /etc/nginx/sites-available/example /etc/nginx/sites-enabled/example

Additionally, delete the default nginx server block.

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

The next step is to install and configure apache.

Install Apache

With nginx taken care of, it’s time to install our backend, apache.

sudo apt-get install apache2

Since nginx is still not turned on, Apache will start running on port 80.

Configure Apache

We need to configure apache to take over the backend, which as we told nginx, will be running on port 8080. Open up the apache ports file to start setting apache on the correct port:

sudo nano /etc/apache2/ports.conf

Find and change the following lines to have apache running on port 8080, accessible only from the localhost:

NameVirtualHost 127.0.0.1:8080
Listen 127.0.0.1:8080

Save and Exit.

Subsequently, open up a new virtual host file, copying the layout from the default apache file:

sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/example
sudo nano /etc/apache2/sites-available/example

The main issue that needs to be addressed here is that the virtual host needs to be, once again, running on port 8080 (instead of the default 80 given to nginx).

The line should look like this:

<VirtualHost 127.0.0.1:8080>

Make sure your Document Root is correct. Save and exit the file and activate that virtual host:

sudo a2ensite example

Before we start testing anything out, we need to equip apache with php. Go ahead and install it now:

 sudo apt-get install php5

Restart both servers to make the changes effective:

sudo service apache2 restart
sudo service nginx restart

Finish Up

We have set up the VPS with nginx running on the front end of our site and apache processing php on the back end. Loading our domain will take us to our site’s default page.

We can check that information is being routed to apache is working by running a common php script.

Go ahead and create the php.info file:

sudo nano /var/www/info.php

Paste the following lines into that file:

<?
phpinfo( );
?>

Save and exit.

Visiting your domain/info.php should show you php info screen, and you’ll be able to see that this was handled by apache. (screenshot here)

Finally, you can see which ports are open and which application is on each one by typing in this command.

sudo netstat -plunt

See More

Configuring nginx and Apache together can be a great boost to a server, and this was just a brief overview. If you have any specific questions about the configuring the two together, feel free to post your questions in our Q&A Forum and we’ll be happy to answer them.

By Etel Sverdlov

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
187 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Very, very good!

setup everything following the steps but only loads default nginx page from /usr/share/nginx/www instead from the /var/www

How does one get this working?

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
October 22, 2012

After updating your root path did you give nginx a restart?

Etel Sverdlov
DigitalOcean Employee
DigitalOcean Employee badge
October 22, 2012

It may also be that the default nginx page is showing up. You can disable the default nginx server block by removing it from the sites-enabled folder. I have added this step to the tutorial in “Configure nginx” step.

jason54886
DigitalOcean Employee
DigitalOcean Employee badge
November 8, 2012

Hi, in the example nginx.conf, in the PHP section, you have written “127.0.0.1:9000” in one place and “127.0.0.1:8080” in another. Is this intentional?

Etel Sverdlov
DigitalOcean Employee
DigitalOcean Employee badge
November 8, 2012

Hi Jason—thanks for catching that. It was a typo that originated because the configuration was based on the the default configs, and I had not removed that comment. It is gone now!

Thanks!

It’s awesome Etel, I’m trying Nginx+Apache on an Ubuntu 12.04, and found that the setting works right-away for most pages. However, the cgi calls seems to stuck on Nginx. I’ve tried adding the following, location ~ .cgi$ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; proxy_pass http://127.0.0.1:8080; } but no luck. Any comments?

jeff
DigitalOcean Employee
DigitalOcean Employee badge
November 27, 2012

jessehaung, I think that question might be outside the scope of this article. (I don’t know the answer off hand just by looking at your syntax).

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
November 27, 2012

Hi Jesse,

Given that the request is being redirected back to your Apache server at http://127.0.0.1:8080 you should attempt to make that request directly to the Apache server to see if its processing correctly:

telnet 127.0.0.1 8080

GET /path/to/script.php HTTP/1.1 Host: domain.com

Then you will see if Apache is returning any kind of weird behavior. Since nginx is just serving as a reverse proxy and it isn’t returning its own error it may be breaking down there.

So you would want to test each piece individually to narrow down where you may be running into an issue.

Jesse, I just wanted to let you know, more than 2 years after you posted this tip, to try telnet, with the specific instructions, this was hugely helpful to some dude (me). I had heard of telnet, but had no idea it could be used test Apache set up. It wasn’t long after trying what you suggested that I was able to get nginx running a reverse proxy to Apache, with right pho info coming back. :thumbs-up:

This worked perfectly. Thank You!

Question: If i’m going to be using wordpress, will I need to create a seperate nginx virtual hosts file for wordpress?

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
December 19, 2012

You do not to create a separate config per domain, that’s really user preference.

If the wordpress instance will be on a totally separate domain than any other domain you will need to create a new server { } block definition for it but you can put that inside of your main nginx.conf if you prefer.

Hello,

How to do this on a live website? Meaning I want to put nginx in front of Apache on a live setup.

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
December 19, 2012

We’re going to update the documentation so that it mimics a live website which will make it clearer how the reverse proxy is working.

Otherwise we end up with two localhost 127.0.0.1 configs and it can be confusing.

Thanks for writing it, it should be updated hopefully by the end of today. =]

Moisey Uretsky
DigitalOcean Employee
DigitalOcean Employee badge
December 19, 2012

We’ve cleared out a lot of the comments from the nginx config.

You will see that the server { } definition in the nginx config has a : Listen 80 Directive, which means that it’s listening on all IPs with port 80 so if you have a public IP configured on the server it will be listening.

Then the server_name directive determines which domains will be served.

The reverse proxy directive then sends requests to 127.0.0.1:8080 which is the IP and Port that Apache runs on.

This is because Apache and Nginx can not both listen on the same IP and port. This way when nginx can not handle a request it will reverse proxy it back to Apache on 127.0.0.1:8080, let Apache handle the response and send it back through Nginx.

Hopefully that clears it up for. But if you have any specific questions please let us know.

Does anyone have any experience working with HaProxy as a front end webserver and apache processing the backend? I was going to use nginx but i was getting the redirect error after installing wordpress… “redirecting in a way that will never complete”. I couldnt get that resolved after reading and trying multiple resolutions. I’m now using haproxy on port 80 and apache on port 8080, everything works great. I just need to rewrite my frontend http_proxy in my haproxy.cfg file, can anyone help possibly?

Hi! I followed your tuts and it worked like breeze. I was hoping that you should make your tutorial a little bit complete for the sake of other beginners like me. 'Twas okay overall though. And also, if you want to use Varnish, you can direct your Apache to port 8888, Nginx to 8080 and Varnish to port 80. Dunno if varnish will work (I’m about to try), but I’ve tried Apache with port 8888 and Nginx with 80 and it worked. Thanks again!

Hello,

I followed all the steps properly. Then installed mysql and setup a php script on the server. However, all .php files are loading fine but none of the .html files are loading. When the browser requests a .html page it loads back to home page. Any fix for this?

Hey Digital , I was going through your : How to Configure Nginx as a Front End Proxy for Apache article and when I get to :

sudo nano /etc/nginx/sites-available/example, I get a blank page.

So I can’t do the modifications required

Is it normal ? I run Ubuntu 12.04 LTS x64 with nginx

Etel Sverdlov
DigitalOcean Employee
DigitalOcean Employee badge
February 27, 2013

That command should give you a blank page as there is nothing there. You can fill in the page with the configuration in the article.

Additionally, you don’t have to call it /example, you can give it whatever name is convenient for you.

Could someone help ? Just did this install and in trying to install phpMyAdmin when I get to restart my apache2 server after installing phpmyadmin

I get this error when trying to access the panel through my browser :

The requested URL /index.php was not found on this server. Apache/2.2.22 (Ubuntu) Server at 198.211.101.100 Port 8080

How can I solve this ?

i am trying to set up owncloud with this nginx / apache2 setup suggested in the article.

the owncloud install suggests another nginx config file. I am a bit lost with servernames, redirection and .htaccess.

http://doc.owncloud.org/server/4.5/admin_manual/installation.html

please help me figure out what configuration changes wouls be needed in order to run owncloud in this setup.

rafael

Is there really much of a benefit to doing this in 2013? I have a MT server setup similarly but most benchmark’s I’ve seen now say Nginx, if properly configured, can handle the PHP with PHP-FPM all on its own just as well or better.

I am new at server setup. So, I got the idea that it would be awesome to combine fastCGI with nginx/apache. Google has nothing for any set that sounds like that, so I kind figured out, but am not sure, running nginx with apache includes something fastCGI already. Can you possibly tell me if that is right?

With set ups today, no, there is no benefit. The standard Wordpress.com set up would be even faster. Properly configured Nginx, php-fpm and mysql, utilizing memcache and the batcache plugin will be much faster. It’s getting fairly easy to get around Wordpress’s scalability issues, but even on smaller cloud servers, 512MB Ram and possibly 1GB Ram, the killer will be Php-fpm, it uses a lot of resources when traffic grows. For a developer working with Wordpress on a cloud server, New Relic (even the free account) can show you a lot of information that you would normally ever ever think about. I don’t recommend many products but New Relic’s system has definitively played a major part in what I do every day. Check out the wordpress optmization article by the guy from Mashable.com, http://blog.newrelic.com/2013/02/07/web-performance-optimization-automation/

If i install varnish, will be config nginx listen port?

I followed the directions and installed my wordpress, but ended up with a redirect loop error.

The wp-admin page loads fine. Any idea?

A cloned version of this article for CentOS would be nice as well =]

It’s working. What do I have to do, to make phpmyadmin works after this config???

I had to the do similar setup with one of my servers. I had to install mod_rpaf ( http://stderr.net/apache/rpaf/ ) because apache was getting 127.0.0.1 as remote_addr field.

Like many people before me, I want to know how to run phpmyadmin using this configuration. I have added location /phpmyadmin { index index.php index.html index.htm; proxy_pass http://127.0.0.1:8080/phpmyadmin; allow 1.1.1.1; #deny all; } to /etc/nginx/sites-enabled/example but that does not seem to work.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
May 28, 2013

@Prasenjit: Check both nginx’s error logs and apache’s error logs.

Hi! It all seems to work (almost). The PHP is showing the info.php page correctly and nginx is working on port 80.

But I do bump into two problems:

  1. nginx now shows “403 Forbidden” on the domain (but not on the info.php, as this is executed via PHP, which must mean that it’s just an nginx permission issue?)
  2. When restarting Apache I keep getting “[warn] default VirtualHost overlap on port 80”

Please advise

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
June 11, 2013

Did you configure apache to listen on port 8080?

Yes. Executing “sudo netstat -plunt” shows nginx listening on “0 0.0.0.0:80” and apache on “127.0.0.1:8080”. I used to have another VirtualHost on this server before but I believe I deleted everything (/etc/nginx/sites-enabled/oldfile).

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
June 11, 2013
  1. When restarting Apache I keep getting “[warn] default VirtualHost overlap on port 80”

Delete the default virtualhost for sites-enabled.

  1. nginx now shows “403 Forbidden” on the domain (but not on the info.php, as this is executed via PHP, which must mean that it’s just an nginx permission issue?)

Try browsing to yourdomain:8080 - does it still return a 403 forbidden error? (You should also temporarily replace 127.0.0.1 with 0.0.0.0 in /etc/apache2/ports.conf so you can access it from your end)

Hi Kamal. Thanks for sticking with.

There was indeed a duplicate of a virtualhost, but in apache2/site-enabled and not in nginx/site-enabled like I was looking for. This sorted the port 80 overlap.

As for the 403 Forbidden issue, I had my Apache virtualhost root directory set wrong and it wasn’t picking up any index.php files (as there were no files in that directory).

Thanks for the help.

My new problem now is that going to the domain in the browser results in a redirect loop. Don’t even know where to start looking for the logs on this one.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
June 12, 2013

Awesome, glad you solved the other two errors! As for the redirect loop --do you have any rewrite/redirect rules in your apache/nginx config files? If so, please pastebin your nginx and apache virtualhosts.

I actually felt frustrated enough that I already wiped everything and started over. Hopefully that will help. Will let you know how it goes. Thanks! :)

Hi, again. I set up the server with nginx handling static files and passing on PHP files to Apache. However, I bump into this problem: the server will display the homepage correctly but then when you start clicking around the page just refreshes despite the URLs changing. It’s probably easier to see than describe so please have a look:

http://miaoxren.cn will load the website first through nginx and then pass it to Apache if it’s PHP but content doesn’t load properly

http://miaoxren.cn:8080 will load the website using Apache, everything works correctly

Now, I assume the problem arises because: A) I assumed this article is about making nginx a reverse proxy to Apache, while it’s really about making it a forward proxy (the title is slightly confusing) and there is a difference that I’ve failed to grasp; B) the actual software installed is the culprit; or C) I’m still missing something from my server configuration

P.S. If this post is too much as a comment for this article, I’m happy to move it to PM or elsewhere.

Thanks!

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
June 17, 2013

@witolot please pastebin both of your Apache and nginx virtualhost config files.

I’ve setup everything and modified some other stuff to my liking, however as stated by another user, a fresh Wordpress install gives a redirect loop error on the index page. The dashboard works fine. To get around that error, I had to add remove_filter(‘template_redirect’, ‘redirect_canonical’); to the theme’s functions.php file.

Now I try to enable friendly urls with the .htaccess and it doesn;t work, it just reloads the same page no matter what I click. Is there something I’m missing?

My Nginx server block: https://paste8.com/KPMSQwXN My Apache vhost: https://paste8.com/q6BwHube

Any help is appreciated.

Hi, sorry for the late response. Got locked out of my server for a while.

Here’s the Apache vhost: https://paste8.com/u30dvSbA Here’s the nginx vhost: https://paste8.com/WgahfRpk

Thanks!

I managed to fix my issue with the redirect loop and such:

my old Nginx server block: https://paste8.com/KPMSQwXN my new nginx server block: https://paste8.com/AetMDiCe

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
June 22, 2013

@rene.peter18: Your new config makes nginx proxy all requests to apache, so it’s proxying static requests as well. If you don’t need Apache, I recommend getting rid of it completely and using nginx with php5-fpm.

Hi, hopefully someone can help me with a problem. I’ve followed the guide above and it works fine for what i’ll term a single virtual host, but when I try to multiple virtual hosts apache seems to fall over.

Firstly is this setup supported?

If so the nginx bit works fine and selects the correct site root for different domains using this config: http://f.cl.ly/items/0E1K2F3J1E3S0b2e1S1u/calcifer-nginx.txt

But apache only ever uses the first virtualhost regardless of the domain used using this config: http://f.cl.ly/items/1431313G2J160p3D0C3X/calcifer-apache.txt

I get no errors when starting nginx or apache but trying to access either domain using :8080 gives a timeout error in chrome (I changed the 127.0.0.1 parts of the config to 0.0.0.0)

Has anyone tried to do this and succeeded? I’ve probably made a silly config error somewhere along the line!

Felix :)

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
June 26, 2013

Try changing setting apache’s Virtualhosts to listen on *:80 and restarting apache. Run ‘netstat -plutn | grep 8080’ --do you see apache there?

simple question. If I installed Nginx as a front end proxy for Apache, can I still use .htaccess as normally? Thanks

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 9, 2013

@proxyland: Yes. :]

Hi there, so what if you have apache sites that are normally on port 80 and some ssl sites too on port 443?

Could you include that in your tutorial?

Thanks!

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 26, 2013

@rjpitt: Adding in SSL encryption between nginx and apache is useless. It just adds more overhead and slows down the requests. You should have nginx serve the SSL cert and proxy the requests to Apache on port 80 (non-SSL).

How can I use this with Virtualmin? I seen a guide here but it would be great if Virtualmin instructions were included with this guide on digitalocean http://hartlessbydesign.com/blog/view/206-virtualmin-apache-and-nginx-reverse-proxy.html

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 31, 2013

@the8thsite: I would recommend not installing it if you have Virtualmin installed as it will break Virtualmin.

Hello, I installed this and it seems like any index.php file redirects the the initial PHP file loaded which happens to be the login screen to my website. for instance, www.example.com/login is the location of the initial login but going to www.example.com/testing/index.php goes back to example.com/login

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 9, 2013

@skyaccessorg: Do you have any redirects in your script? Do you have an .htaccess file? If so, please pastebin it.

There are a few other .htaccess files in the directories but this is the one in the main /var/www

http://pastebin.com/6KmZU9j9

Note: The other .htaccess files come from the installation of software such as Amember and Vbulletin/MyBB :)

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 10, 2013

@skyaccessorg: Try commenting them out, or moving .htaccess to .htaccess.bak e.g., does it work without it?

Well without them the rules don’t stand and the path to the Amember login redirects to the main login on the website.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 10, 2013

@skyaccessorg: Do you have multiple applications on the same domain? (in /var/www)

The applications have their own folders, and .htaccess is used to detect the domain and refer them to the appropriate folder.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 11, 2013

@skyaccessorg: Why are you doing that? I recommend setting up a virtualhost for each domain name: https://www.digitalocean.com/community/articles/how-to-set-up-apache-virtual-hosts-on-ubuntu-12-04-lts

Hello! Great tutorial. Just a quick question in regards to another one of your comments: @rjpitt: Adding in SSL encryption between nginx and apache is useless. It just adds more overhead and slows down the requests. You should have nginx serve the SSL cert and proxy the requests to Apache on port 80 (non-SSL).

– HOW do you do this?

I have added this to /etc/nginx/sites-available/nameofsite

HTTPS server

server { listen 443; server_name sitedomain.com;

    root /var/www/;
    index index.html index.htm index.php;

    ssl on;
    ssl_certificate /ssl/sitedomain.com/sitedomain_combined.crt;
    ssl_certificate_key /ssl/sitedomain.com/www.sitedomain.com.key;

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

    location ~ \.php$ {

    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8090;
     }

     location ~ /\.ht {
            deny all;
    }

}

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 12, 2013

@david: That config file looks valid – are you experiencing any problems with it?

Hi Kamal,

Well, I thought I was! ;)

But, must have just been a caching issue because it’s working brilliantly now!

The issue I was having was that when I went to the HTTPS version of the web URL, it attempted to download the PHP file. Telling me that NGINX wasn’t properly proxying the HTTPS PHP request to Apache. But, now all seems right with the world.

Thanks for your assistance. Hopefully my oversight will help other users!

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 15, 2013

Awesome! Glad I could’ve been of help :]

Hi, thanks for the tuto. I have a ssl server in apache and tried to follow it with some changes for ssl. First of all I edited apached ports.conf and /etc/apache2/sites-available/example and delete de mod_ssl things and using port 80 instead of 8080. Nginx sites-available is now like this:

server { listen 443;

    root /var/www/;
    index index.php index.html index.htm;

    server_name         www.mydomain.com;
    ssl on;
    ssl_certificate /etc/ssl/certs/mydomain_com.crt;
    ssl_certificate_key /etc/ssl/private/mydomain.key;
    #enables SSLv3/TLSv1, but not SSLv2 which is weak and should no longer be used.
    ssl_protocols SSLv3 TLSv1;
    #Disables all weak ciphers
    ssl_ciphers ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM;

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

    location ~ \.php$ {

    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:80;
    proxy_redirect http:// https://;

     }

     location ~ /\.ht {
            deny all; 
    }

}

So, i restarted both nginx and apache and now I have apache listening on port 80 and nginx listening on port 443. I can access to the index, but is ignoring my .htaccess file and http:// is not redirecting to https;// is giving error.

What am I doing wrong?? Thanks in advance!

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 16, 2013

@sobrelaweb: Why do you have apache on port 80 and nginx on port 443? You should have nginx on port 80 and 443, and apache on port 8080;

Set up two virtualhosts for nginx, one for ssl and one for non-ssl, both should reverse proxy to 127.0.0.1:8080, also delete the “proxy_redirect http:// https://” line.

Nginx should handle SSL, apache should only serve content to nginx.

@Karmal, thanks for the answer. Ok, now I have: server { listen 80; … like here in the tutorial }

server { listen 443; … like my last comment }

and “proxy_redirect http:// https://” line removed

apache configured like the tutorial and listen on port 8080

So I can access https:// and http:// but .htaccess is not readed. I have to redirect every http to https, to show always https. In apache I had this line: <VirtualHost *:80> RedirectPermanent / https://www.verifybtc.com/ </VirtualHost> <VirtualHost *:443> …SSL conf <VIrtualHost>

Now I changed it to: <VirtualHost 127.0.0.1:8080> Normal conf </VirtualHost>

So SSL is managed by nginx, isn’t it? I’m missing something, but I don’t know why http is not being redirected to https? Should I conf something on nginx? What is it? And then, why my htaccess is not being readed?

For example. this one: RewriteRule ^panel index.php?page=panel [L]

Thanks for your attention and help.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 16, 2013

Even if you browse to https://, apache will think you’re on http. You should set up the http->https redirect in nginx.

Replace your http server block with this:

<pre>server { listen 80; server_name www.yourdomain.com yourdomain.com;

rewrite ^(.*)$ https://yourdomain.com$1 permanent;

}</pre>

Thanks again, it worked. But still not reading the htaccess file well:

RewriteEngine On RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC] RewriteRule ^(.*)$ https://domain.com/$1 [L,R=301] RewriteRule ^panel index.php?page=panel [L]

Two first lines to redirect www.domain.com to domain.com without www is working ok. Panel line with frinedly url is not working. All worked fine on apache. Any idea?? Should I put it on nginx instead htaccess? or where?

Thanks again!

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 16, 2013

@sobrelaweb: This set up only proxies .php files to Apache, add this rule to nginx:

<pre>rewrite ^/panel /index.php?page=panel;</pre>

Thanks again, finally it worked on the 443 config!

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 16, 2013

Sweet! :]

Hello Kamal,

I have read the article and used same configuration in my vps. now I installed the wordpress on the server, the install progress is ok. but when I tried to access http://myipaddress/, chrome shows redirect loops. (dashboard access is ok, http://myipaddress/wp-admin can be opened normally)

I am wondering if this configuration works on wordpress?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
August 31, 2013

@lanjunq: Check nginx’s and apache’s error logs – do you see anything?

Hi Kamal,

I’m getting The requested URL /index.php was not found on this server. at my DocumentRoot.

Here is my nginx main file: http://pastebin.com/Qv1zV633

I’m sure an index.php exists in that folder. It’s a wordpress setup.

In regards to my last comment I’m not having that problem anymore, instead I’m having redirect loops.

This is my main file with nginx being a frontend for apace and having all dynamic pages forwarded to apache2: http://pastebin.com/Tm7BT9qX This results in a redirect loop unfortunately with wordpress.

When I use this configuration, the website loads fine, although nginx is handling all static and dynamic content which is against the point. http://pastebin.com/X8HCGGZW

Any help would be appreciated :)

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 5, 2013

@stmeter: Nginx can’t handle dynamic content with your current setup. It only passes it to apache.

Can you please pastebin your apache virtualhost config and check the error logs for any erorrs?

Hi according to this tutorial i configured my server (ubuntu 12.10) plus i did install apc then i install WordPress. But the problem is when i tried to open my domain i got this error “This webpage has a redirect loop” on the other side “mydomain.com/wp-admin” working perfectly. So anybody have any idea to solve this situation ??

2013/09/13 14:30:28 [error] 16260#0: *120 directory index of “/var/www/” is forbidden, client: 123.125.71.19, server: ninthfact.com, request: “GET / HTTP/1.1”, host: “www.thefuckingweatheryo.com” 2013/09/13 14:32:01 [error] 16260#0: *121 directory index of “/var/www/” is forbidden, client: 220.181.108.91, server: ninthfact.com, request: “GET / HTTP/1.1”, host: “www.thefuckingweatheryo.com” 2013/09/13 14:32:47 [error] 16260#0: *122 directory index of “/var/www/” is forbidden, client: 108.162.231.248, server: ninthfact.com, request: “GET / HTTP/1.1”, host: “ninthfact.com

this was my nginx error log. and i don’t understand. why this “www.thefuckingweatheryo.com” donain pointing to my droplet ??

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 15, 2013

@ninthfact: Please pastebin apache and nginx’s config files.

Is possible to put varnish + apache + nginx in one box ?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 24, 2013

@mas: Yes - you can have Varnish listening on port 80, nginx on port 8000 e.g., and apache on port 8001. The ports don’t really matter, they can be anything you want but keep in mind that Varnish has to listen on port 80.

i set Nginx listen on 80 with static content and Apache on 8080 as your tutorial. But some images don’t work with Nginx ( 404 error ) : mywebsite.com/images/1.png : error 404. mywebsite.com:8080/images/1.png : ok. This is my Nginx.conf :

server { listen myipaddress:80;

    server_name www.vietmoonlight.com;

location ~ “.pagespeed.([a-z].)?[a-z]{2}.[^.]{10}.[^.]+” { add_header “” “”; } location ~ “^/ngx_pagespeed_static/” { } location ~ “^/ngx_pagespeed_beacon$” { } location /ngx_pagespeed_statistics { allow 127.0.0.1; deny all; } location /ngx_pagespeed_message { allow 127.0.0.1; deny all; } location /pagespeed_console { allow 127.0.0.1; deny all; } location / { proxy_pass http://myipaddress:8080; include /usr/local/nginx/conf/proxy.conf; }

    location ~* ^.+\.(jpe?g|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mp3)$ {
               expires 30d;
               root /home/mywebsite.com/public_html;
               }
     location ~ /\.ht {
            deny all;
    }

}


Chown images : www-data

What should i do now ?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
September 30, 2013

@hotro: Does <code>/home/mywebsite.com/public_html/images/1.png</code> exist?

Please pastebin apache and nginx’s config on pastebin.com or a similar service.

yes, it is. Love Nginx’ speed, but always have some problems with him :). Maybe i will try to use litespeed

Hi everyone, I’m new here

I can access to my website with Nginx already but when I click every links in my web the URL changed but the page redirect to homepage. I can’t even log in to my admin panel. Please Help me

here is my example on nginx : http://pastebin.com/3d8EVjm4 here is my example on apache2 : http://pastebin.com/xumtYWuh

thanks

Great guide, easily setup first try. Was wondering, with this setup would sub.domains be managed via Apache? or Nginx? or both?

I’ve managed to get this to work for my root domain, with apache running on :8989 and nginx on port 80.

What is the correct way to redirect www.example.com to example.com?

here’s my non-working sites-enabled/domain.com config: http://pastebin.com/mUT1ffSr

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
October 9, 2013

@bd: The easiest way to redirect www. to non-www is creating a separate nginx virtualhost:

<a href=“https://p.kk7.me/cukicomohi.nginx”>https://p.kk7.me/cukicomohi.nginx</a>

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
October 9, 2013

@lippiltv: Does it work when it’s served by apache? (http://ip:8080)

So lets clear the things:

If phpmyadmin get redirect loop insert this line to config.inc.php $cfg[‘PmaAbsoluteUri’] = ‘http://your.ip/phpmyadmin/’;

If wordpress get redirect loop install the permalink-fix-disable-canonical-redirects-pack from wordpress plugin site

thats all

I hope it helps a lot ;))

Has anyone compared this two different configurations? a) LEMP (PHP-FPM) b) Nginx as a Front End Proxy for Apache

Exp: Lets say Apache is already installed do you do the same steps or ? skip it and go to NGINX?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
October 18, 2013

@h3r0k0: You can then skip the ‘Install Apache’ section.

I have a Question: In Step 8 is this: NameVirtualHost 127.0.0.1:8080 Listen 127.0.0.1:8080

In the Standard-File /etc/apache2/ports.conf is this: Listen 80 Listen 443

So I ask now: What about port 443, why do we have port 8080 and not port 80 and why we need the IP-Address before and usually it is not there?

What can i do to have a perfect System? I have Debian Wheezy 64 Bit, i want this Combination from Apache2 and Nginx and then i want a good running Froxlor-0.9.29-Panel on it.

What can i do to make it true? Please help me !!!

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
October 20, 2013

@Xchanger: Listen 443 is for SSL. Nginx should handle SSL and not apache if you’re going to use nginx as a reverse proxy so you can comment out that line.

Nginx is listening on port 80 so apache has to listen on another port, you can use any (unused) port you want but it’s common to use port 8080.

I don’t recommend installing Froxlor. If you want to use Froxlor I recommend installing it on a fresh new droplet and <strong>not</strong> editing any config files manually/installing packages which would probably break Froxlor.

i have followed the intructions but i ned up with

<? phpinfo(); ?> on my web page instead of the php information page

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
October 24, 2013

@mobin.kurien.web: Is Apache installed? Please pastebin your nginx virtualhost file.

how to use this with varnish ?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
November 22, 2013

@henriquesacramento: See my comment above (<code>September 24th, 2013 12:32</code>).

Seems like the same problem as @witolot had. Server displays homepage correctly, but when you click links on the page, it just refreshes despite the fact that URL’s are changing.

Thank you for the article! I’ve just used it to create a nginx-apache configuration for drupal (nginx as front-end serving cached files and apache on backend), here’s my configuration (with apache configured on port 8080):

server { listen 80; server_name www.myname.ru; root /home/mynamedata/www;

location ~ ^/sites/.*/files/ {
try_files $uri @proxy;
}

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

location @proxy {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;
proxy_pass http://127.0.0.1:8080;
}

}

It works as i want, but i had to repeat myself twice the same proxy-pass.

I have a problem with this configuration that I saw before trying it and I’d love to know if there is a solution. The nginx server decides that something is a 404 without checking with Apache. Let me give an example. Let’s say you want to use .htaccess to redirect /google to http://google.com. When the request hits nginx, it knows that there is no /google so it responds with a 404. I know I have apache configured correctly. If I use curl from the command line to check curl localhost:8080/google I get a 300 response. It’s important for most web servers to give full capability to Apache for this type of redirect. Is the only solution to have the file present in the root directory so the request gets forwarded to apache? Or would it be better to take the opposite approach, specify which static files you want nginx to serve the proxy the rest?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
December 14, 2013

@ryan.burnette: Please pastebin apache’s and nginx’s config files.

I am able to proxy from nginx to apache EXCEPT if I try to use SEO friendly urls <domain>/article-name-here. Here is a pastebin: http://pastebin.com/Shi7jxNA

This is a wordpress site. I am also trying to wire up the plugin WPML. I requests that I test .htaccess using: <domain>/en/?____icl_validate_domain=1

This is the relevant .htaccess:

BEGIN WordPress

<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule>

END WordPress

Thank you for any observations. :)

After further consideration, I realized that it is possible to scrap apache altogether. Just use nginx. :)

I followed these directions exactly. When I visit ip-address/info.php in my browser it tries to download info.php rather than display it. How to fix?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
February 22, 2014

@larrypack: Can you pastebin your nginx config?

Greetings! I have some problems. CentOS 6.5 + nginx as front-end, apache as back-end + php-fpm as FstCGI. All work, but some links didnt open. For example: Trying go mysite.com/rules & click for some link. I am going at mysite.com/go/rules & nothing happens. Only page refresh. Logs clean :(

NGINX server { listen 80;

    root /srv/www/mysite.com/public_html/; 
    index index.php index.html index.htm;

    server_name mysite.com; 

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

    location ~ \.php$ {
    
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8080;

     }

     location ~ /\.ht {
            deny all;
    }

}

APACHE Listen 127.0.0.1:8080 … LoadModule fastcgi_module modules/mod_fastcgi.so …

Associate an alias mapping for the ‘fake’ fcgi call.

Alias /php5.fcgi /srv/www/mysite.com/public_html/php5.fcgi

Assign the ‘fake’ fcgi to call to an ‘external’ FastCGI Server

FastCGIExternalServer /srv/www/mysite.com/public_html/php5.fcgi -flush -host 127.0.0.1:9000

Create the handler mappings to associate PHP files with a call to ‘/php5.fcgi’

AddType application/x-httpd-fastphp5 .php Action application/x-httpd-fastphp5 /php5.fcgi … NameVirtualHost 127.0.0.1:8080 … <VirtualHost 127.0.0.1:8080> ServerAdmin admin@mysite.com DocumentRoot /srv/www/mysite.com/public_html/ ServerName mysite.com ErrorLog logs/mysite.com-error_log CustomLog logs/mysite.com-access_log common <Directory “/srv/www/mysite.com/public_html”> Options All AllowOverride All Allow from all </Directory> </VirtualHost>

Hello. When I try to grab the visitor’s IP in php using $_SERVER[‘REMOTE_ADDR’] I get 127.0.0.1. Is there any way to get Nginx to pass the real IP to Apache?

Here is the fix for getting Nginx to pass the IP to Apache: http://chrismorris.org/passing-ip-from-nginx-to-apache/

great tut. There are some questions I want to know their answers if possible.

1- is it possible to use either php-fpm or php Fascgi with the production as explained above?

2- how about if I have a subdomain such as static.forexmegacashback.net and a domain www.forexmegacashback.com; two different sites under one droplet, where the static files on the subdomain and the dynamic contents under the domain?? is there something I need to add or should I create new vhost in this case??

any idea?

Thanks @Kamal for the reply.

There is another question if you don’t mind. my site is going to host a forum community which means a lot of users therefore a lot of connections. In such case Apache is the only web server that can handle multiple connections with heavy load traffic. This is why I want to use Nginx reverse proxy at the front end Apache. so Apache will handle the dynamic contents and Nginx will handle the static files such as css, js and images.

Now my question is, what about if I want to serve the static files from a subdomain .net to the domain .com, is that different settings??

I will try to create another vhost for my subdomain and see how I can serve the files to the main domain

Thanks

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
March 5, 2014

@FMCB: <blockquote>In such case Apache is the only web server that can handle multiple connections with heavy load traffic.</blockquote>That’s incorrect. Apache is known for its high memory usage when there are a lot of concurrent connections. Nginx handles dynamic content just fine (e.g. wordpress.com use nginx).

Thanks @Kamal for correcting me.

I will test both Nginx + php-fpm and Nginx reverse proxy at front end Apache.

Regards,

Hi,

I want to use nginx (listens on port 80) to proxy a Wordpress site served by Apache (8080). The problem is that somewhere on the way it redirects the request from mnm.chef.muszek.com to mnm.chef.muszek.com:8080. Please offer some advice.

My nginx config: https://paste8.com/aGPxjjVD Apache vhost (the rest is pretty much a default Debian config): https://paste8.com/Kuk7Les1

More info: the redirect seems to happen on all the usual “content” URLs. The admin panel (/wp-config) seems to work properly (there’s no redirect).

I managed to fix the problem.

  1. I changed the url from domain.tld:8080 to domain.tld in /wp-admin/options-general.php (2 places)

  2. Wordpress started going into a redirect loop. I installed https://wordpress.org/plugins/permalink-fix-disable-canonical-redirects-pack/ as someone else suggested and it fixed that problem.

I am having permission issue with apache. I find that the php files are being redirected to apache properly but get a 403 forbidden error. On a ubuntu 12.04 droplet with apache 2.4.6 and nginx 1.1.9 .

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
April 1, 2014

@arul.smartpixels: Check both Apache’s and nginx’s error logs (/var/log/apache2/error.log and /var/log/nginx/error.log respectively). Is there anything in there on why it’s returning a 403 error?

Excellent stuff Etel.

I’m running nginx on Ubuntu 12.10 with 5 web apps in one box, AND then Apache on OS X (Mac Mini) with a web photo gallery (gallery3) serving a few thousand pictures and videos. I thought about configuring nginx as a reverse proxy for Apache for all the performance benefits it provides. It should be feasible to have Apache handle the gallery app except the actual media (static pictures and videos), which nginx would be ideal to handle, but I’m not sure on the actual details. Do you have any suggestions?

Angelo C

Hi!

I’m also having a 403 forbidden error, but just in a subdomain I use for a Laravel installation (so far, other html files, php scripts and a wordpress installation work fine).

The subdomain works if I request it directly to apache using :8080 (http://cms.canidaeworks.com:8080) and also works if I request it using nginx BUT directly to the public folder (http://cms.canidaeworks.com/public).

So I’m guessing it has something to do with not having an index.php file on the Laravel root folder and the .htaccess not working somehow when coming from nginx.

I don’t get any errors on the apache error.log but do have this error on de nginx error.log:

2014/04/23 15:36:11 [error] 1216#0: *117 directory index of “/var/www/html/cms/” is forbidden, client: <blabla ip>, server: cms.canidaeworks.com, request: “GET / HTTP/1.1”, host: “cms.canidaeworks.com

Everything inside var/www/html is owned by apache and on group apache.

Hope you have some idea on what might be happening! Great tutorial btw

Diego.

Andrew SB
DigitalOcean Employee
DigitalOcean Employee badge
April 23, 2014

@wolfius: Could you pastebin the nginx server block and apache virtual host for the subdomain?

Sure,

ngnix: http://pastebin.com/MDRCYNPD

apache: http://pastebin.com/370SxPXX

Now that I saw it, it ocurred to me to change de root path on nginx server block to include the “public” folder, it works and I could be fine with that, but isn’t it the point to just pass the request to apache and have it deal with it as if it were it’s own?

Andrew SB
DigitalOcean Employee
DigitalOcean Employee badge
April 23, 2014

@wolfius: I’m actually a bit surprised that it is available over port 8080. What happens if you set the VirtualHost’s DocumentRoot to /var/www/html/cms/public

@Andrew Still doesn’t work on nginx but does work on apache, BUT, doing some reading on Laravel forums I remembered that ACTUALLY the “correct” thing to do is to point the DocumentRoot to the public folder and not to use an .htaccess on the root folder. I was implementing it like that because I copied the project from a shared server where I couldn’t mess with those config files :)

So, I guess my “problem” is kind of pointless now haha, thanks for trying to help though!

I already have apache2 running on my site, but I am having memory problems and want to set up nginx, but how would this process differ with apache already installed and in use? I tried following the tutorial and got an infinite loop, then a 502 error so I recovered from a backup. Any ideas?

I configured site successfully, but images from sites are not showing. txt and phpinfo working fine.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
May 29, 2014

@bineeshoc: Do you get a 404 error page? If so, is it nginx’s or apache’s? Check both webservers’ error logs and see if you can find any details on why you’re getting a 404 error: <pre>sudo tail /var/log/apache2/error.log sudo tail /var/log/nginx/error.log</pre>

Setup Varnish :80 NGINX :8080 & Apache :8888 + PHP & MySQL

index.html & info.php worked

I installed Magento now I get

http://104.131.230.208:80 “This webpage has a redirect loop” http://104.131.230.208::8080 “This webpage has a redirect loop” http://104.131.230.208::8888 The Magento installation page

Anyone know how I can resolve the loop problem?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 2, 2014

@email: None of these are loading for me – are you still experiencing this issue or have you destroyed the droplet?

@ Kamal Nasser

I destroyed the droplet to save some money. I created a snapshot first, so it’s back up now, same IP. Thanks for taking a look!

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 2, 2014

@email: Try installing Magento (:8888/index.php/install/ first and then browsing to it through Varnish. I wouldn’t use both nginx and Varnish as both are used to serve static files only in your case so using both might introduce some new issues. Try stopping Varnish and using nginx -> Apache only. Let me know how that goes!

Hi, I have installed nginx as reverse proxy following all the above instructions but have one confusion:

when i type “http://localhost:8080/info.php” in my browser it shows me proper result but when i type this “http://localhost/info.php” then an error is shown “Unable to connect”.

What is the issue? please help me :(

Sorry buddies, Issue has been fixed I have not restarted nginx. after writing following line all is going well here sudo service nginx restart Really, a superb tutorial :) now i am happy.

Hi, I installed LAMP and completed and created 2 virtual hosts with wordpress installed. Now i’m planning to add Nginx. Is it possible to install Nginx after Apache installed? which is best for wordpress website for best results, LAMP or LEMP or this medthod? Please suggest me.

i finally successful installing nginx as reverse proxy but i have a problem with phpmyadmin. images, documentation showing 404 error nginx. Please help me with this.

I’m using 2gb RAM, 40gb droplet with centos 6.5 + LAMP +nginx as reverse proxy.

i solved this

http://www.bentasker.co.uk/documentation/linux/200-configuring-nginx-to-act-as-a-reverse-proxy-for-phpmyadmin

Solution: adding phpmyadmin location to each server block.

i tried this solution 2 days back and it didnt work as i was trying with only one server block

Hi, I did everything as mentioned above and it’s okey. But I got error on domain home page


" It works!

This is the default web page for this server.

The web server software is running but no content has been added, yet."


What’s wrong ? thanks

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
July 30, 2014

@iedemirci: Are your accessing our website using your domain name or your IP address? Make sure Apache’s ServerName matches nginx’s server_name.

I ran into the following errors when installing Apache:

* Starting web server apache2                                                                                                                                                       AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
(98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
(98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
AH00015: Unable to open logs
Action 'start' failed.
The Apache error log may have more information.

Then:

me@hostname:~$ sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/example
cp: cannot stat ‘/etc/apache2/sites-available/default’: No such file or directory

Ok, fixed those. Used 000-default.conf instead of default for the apache2/sites-available. Yet, I couldn’t do this:

me@hostname:~$ sudo a2ensite example
ERROR: Site example does not exist!

So I renamed it to example.conf and it worked.

Andrew SB
DigitalOcean Employee
DigitalOcean Employee badge
August 6, 2014

@phil: It should be the name of the file. So if the file is /etc/apache2/sites-available/000-default.conf then the command would be:

sudo a2ensite 000-default.conf

Hi all,

Below is my config in sites-available, But when i start nginx i get and error [emerg] 20137#0: “proxy_cache” zone “one” is unknown in /etc/nginx/nginx.conf:74

This is happening after i updated ubuntu…Please help

#Node JS App on http port 3000

upstream ci{
	server 127.0.0.1:3000;
}

#NGINX server instance

server {
	listen 80;
	server_name connectedimaging.com www.connectedimaging.com;
	return 301 https://$host$request_uri;
}

server {
	listen 443;
	ssl on;
	ssl_certificate /etc/nginx/ssl/certs/6c60c8641416.crt;
	ssl_certificate_key /etc/nginx/ssl/certs/connectedimaging.com.key; 
	server_name connectedimaging.com www.connectedimaging.com;
	add_header Strict-Transport-Security max-age=500; 
	access_log  /var/log/nginx/ci_access.log;

        location ~* 
        ^.+\.(jpg|jpeg|woff|ttf|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$ 
{
          root /home/telerad/connectedimaging/public;
          expires 30d;
        }
	
	location / {
		proxy_cache one;
	        proxy_cache_key sfs$request_uri$scheme;
		proxy_pass http://ci/; 
                include /etc/nginx/proxy.conf; proxy_set_header 
		X-Forwarded-Proto https;
	}
}

Hello , why does php not working ? please help me …

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
October 15, 2014

What do you mean by “not working”? Do you get any errors? A blank page? Are there any errors in Apache’s or Nginx’s error logs?

sudo tail -40 /var/log/apache2/error.log /var/log/nginx/error.log

@Kamaln yes thank i had solved…

I hope anyone can help me. I followed all this tutorial and when I go mydomain.com/info.php I can see a blank website. It seems like there was a problem during the installation.

Just a heads up, in Ubuntu 13 /etc/apache2/sites-available/default has been renamed to 000-default.conf

Also, remember to add .conf to the end of your file as well or it won’t be recognized. Use:

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.conf

A very nicely written guide,

I have just one question before I start implementing everything in this guide, suppose I have a full PHP website, and when you say nginx is extremely fast with static content, does that mean entire static pages ?

If my php script loads a lot of images, does these images get handled by Apache since they’re inside the PHP file or does nginx server them ?

Also, does nginx forward all php requests to apache just by looking at the extension (.php) of the file the client is requesting for ?

Greetings,

This is the first time I’m doing any sort of server setup. I’ve followed the guide and most of it seems to be working properly. There seem to be a few anomalies though. All php files to get redirected to apache listening on port 8080.

The setup seems to be acting a little strange in certain scenarios

When I have an index.html file at /var/www/ and I query nginx

  1. Any invalid file with any extension other than .php apache throw an error, further apache always throws a 404 error for /index.php ( regardless of the invalid html file)

  2. All invalid .php files get 404 errors with proper names


When I have an index.php file at /var/www/ and I query nginx

  1. Invalid .html files result in contents of index.php getting displayed

  2. All invalid .php files get 404 errors with proper names


Regardless of whether I have an index.html or an index.php located at /var/www all requests made directly to apache at 8080 like : http://server_ip:8080/index.php result in 404 errors, with correct files names being thrown in errors

PHPMyAdmin on the other hand, works with all possible combinations be it querying nginx or apache directly at 8080.

Any pointers and explanations leading to a solution would be helpful.

My nginx server segment, apache virtual hosts, httpd.conf and ports.conf are include below

Server block : http://pastebin.com/iZszi0kF Virtual Hosts : http://pastebin.com/dveuxyzQ Ports : http://pastebin.com/pXj3CLwd Httpd : http://pastebin.com/ABd75YRU

Thanks in advance !

it’s a powerful config I’m trying it for a wordpress website every thing is good just I receive this message when I go to the frontend

It works! This is the default web page for this server. The web server software is running but no content has been added, yet.

I’m using the IP for my test and not a domain name Kamal suggest to use the IP as a server name on the config of nginx and apache I changed it on nginx but I did’ find the ServerName on apache can you help me with that please

I would like to add Varnish to this configuration can you help me with that please Thanks

it’s a powerful config

I’m trying it for a wordpress website every thing is good just I receive this message when I go to the frontend It works! This is the default web page for this server.

The web server software is running but no content has been added, yet. I’m using the IP for my test and not a domain name Kamal suggest to use the IP as a server name on the config of nginx and apache I changed it on nginx but I did’ find the ServerName on apache can you help me with that please

I would like to add Varnish to this configuration can you help me with that please Thanks

i was using nginx with laravel on ubuntu machine.

now i have followed this and also laravel nginx configuration tutorial here https://www.digitalocean.com/community/tutorials/how-to-install-laravel-with-an-nginx-web-server-on-ubuntu-14-04 to change nginx to reverse proxy for apache

after following the tutorial to configure, i checked the IPs and ports on which service is running on which port/ip via netstat plunt;

apache 127.0.0.0:8080 nginx 0.0.0.0:80

my question is; how can i test/check if the configuration is working OK. because when i stop apache service, the pages are still loading. Is nginx not really reverse proxy or this is OK ?

thx in advance

murphy

I have the impression this tutorial is designed to be used on a newly created droplet or server. The absolute first thing I am doing on the droplet I created is to execute the steps in this tutorial.

In this scenario, there are no domains running on this server. So how does this step work or get accomplished? Visiting your domain/info.php should show you php info screen, and you’ll be able to see that this was handled by apache. (screenshot here)

Thank you in advance for any help provided.

a very good idea, to combine Nginx in front of Apache. I just have applied a dead simple configuration:

upstream backend {
  server localhost:8080;
}

server {
  listen 80;

  location / {
    proxy_pass http://backend;
  }
}

Apache is listening on 127.0.0.1:8080 and therefore more secure (secured by Nginx in front of)

Thnx much for this good idea! :-)

This worked great. Right now, legacysystems.biz is running on the setup explained in this article. Thank you very much for making this possible.

QUESTION: How do add another virtual host for another domain, to run 2 domains from this server. The domains have nothing in common, except I need to run them on the same instance of Ubuntu, if possible. The other domain that needs to run on this droplet is houston-data.com

Sorry if this is a stupid question.

I have followed this tutorial as it is to install the nginix and apache together in a new basic droplet with ubuntu 14.04 64bit but unable to install it successfully. Everything went well till installing apache. When trying to change the ports as below sudo nano /etc/apache2/ports.conf

Find and change the following lines to have apache running on port 8080, accessible only from the localhost:

NameVirtualHost 127.0.0.1:8080 Listen 127.0.0.1:8080

I don’t find this at all and my initial files look like

If you just change the port or add more ports here, you will likely also

have to change the VirtualHost statement in

/etc/apache2/sites-enabled/000-default.conf

Listen 80

<IfModule ssl_module> Listen 443 </IfModule>

<IfModule mod_gnutls.c> Listen 443 </IfModule>

vim: syntax=apache ts=4 sw=4 sts=4 sr noet

In this i have changed Listen 80 to 8080 and added the below two lines at the end of the file. NameVirtualHost 127.0.0.1:8080 Listen 127.0.0.1:8080

And then followed the next steps

Subsequently, open up a new virtual host file, copying the layout from the default apache file:

sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/example sudo nano /etc/apache2/sites-available/example

After opening the file i dont see the line <VirtualHost 127.0.0.1:8080> in the file. Can someone guide me on this

Thanks in Advance and looking forward.

I don’t find this either. But I replaced the

Listen 80

line with the

NameVirtualHost 127.0.0.1:8080
Listen 127.0.0.1:8080

lines. Is it okay? Hope that works.

We will require two droplets here right?

A question about architecture. Is it more efficient to have both nginx/apache on a 1 GB RAM droplet or one on each droplet with 500 MB RAM? Looking to host some small wordpress sites.

For those of you having problems with using this configuration with WordPress, here is the solution. Use this as your NGINX config.

server {
  listen 80;

  server_name domain.com;

  root /var/www/html/;

  index index.php index.html index.html;

  # send anything with .php in it to apache
  location ~* \.php$ {
    try_files /dev/null @proxy;
  }

  # for everything else, 
  location / {
    try_files $uri $uri/ @proxy;
    error_page 404 = @proxy;
  }

  # Deny access to all dotfiles
  location ~ /\. {
    deny all;
  }

  # Named location for reverse proxy
  location @proxy {
    if ( $uri = /index.php ) {
      rewrite /index.php / break;
    }
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8080;
  }
}

As always, make sure to edit server_name and root with your server variables.

It would be much better to mention like this

location ~ .php$ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; proxy_pass http://127.0.0.1:8080;

Hi Etel,Thanks for a wonderful tutorial, I have followed the above steps and configured the settings for both Apache and Nginx. When trying to restart Apache server I am getting the following error

sudo service apache2 restart

  • Restarting web server apache2
    (98)Address already in use: AH00072: make_sock: could not bind to address [::]:8080 (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:8080 no listening sockets available, shutting down AH00015: Unable to open logs Action ‘start’ failed. The Apache error log may have more information.

  • The apache2 instance did not start within 20 seconds. Please read the log files to discover problems

Kindly respond what wrong in the above set up. Thanks in advance

Hi, I read this tutorial to create a user with sudo privileges. I created a new user and disabled the root login on my vps and now I am following this tutorial and I am in

Configure nginx Open up the nginx configuration.

sudo nano /etc/nginx/sites-available/example

I am on windows and using PuTTY and Filezilla so I did not follow that command instead created a file in my computer directory, when I added the code and ready to upload back to server I’m getting an error: /etc/nginx/sites-available/example: open for write: permission denied error: File transfer failed.

And I noticed that /etc/nginx/sites-available/ folder Owner/Group = root root.

Any solutions?

Thanks!

Hi,

Thanks for this great tutorial.

Is there a way to get a tutorial for nginx -> nginx? What I´m looking for is setup a reverse proxy with nginx and forward them to another nginx server. The reverse proxy should forward all traffic to the webserver to a related port.

Nginx Reverse Config: server {

listen 80; listen 443 ssl; ssl on; server_name host1.tld; root /var/www/; index index.html index.htm index.php;

Nginx Webserver server {

listen IP:Port; ->?

Thanks!

Thank you for the tutorial. I can’t quite understand what does it mean by “sudo nano /etc/nginx/sites-available/example” - what is sites-available and example here? Sorry but im very new. (im using centos 6.7)

Did not work for me (ububtu 14.04) Error -> AH00558: apache2: Could not reliably determine the server’s fully qualified domain name, using 127.0.1.1. Set the ‘ServerName’ directive globally to suppress this message (98)Address already in use: AH00072: make_sock: could not bind to address [::]:80 (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down AH00015: Unable to open logs Action ‘start’ failed. The Apache error log may have more information.

Hello,

What if you install hhvm in place of php5? Or install php-fpm or do you go about the configuration?

All was going well, untill this step: -“Subsequently, open up a new virtual host file, copying the layout from the default apache file:”

When I typed, in the terminal,
“sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/example” the response was “cp: cannot stat ‘/etc/apache2/sites-available/default’: No such file or directory”

What should I do?

Thanks for the help ;)

Apparently I fixed the problem using @wrongwhale 's tip and running

sudo a2ensite example

again, then restarting apache and nginx again.

It’s probably fine now, but how to know for sure?

Hello friends, I want to run my php web application run on two server like nginx for html part and apache is for scripting language.so how can i do .please help me for above scenario.

Thank you very much for your perfecto tutorial :)

How current is this guide? i see its kinda short ? also anyone tried HHVM instead of PHP

Its really helpful, thanks so much…

So I’ve got everything built under this, looks like everything is working, except for the fact that checking the host through nginx returns a 403 error. It’s not a permissions error, the directories and files under Apache are fine. It appears that it’s just nginx that’s failing somewhere. I can pull this from the nginx error log:

2016/03/27 19:52:39 [error] 25750#0: *13 directory index of “/var/www/” is forbidden, client: 127.0.0.1, server: example.com, request: “GET / HTTP/1.1”, host: “localhost”

Any Ideas what I fuddled up?

Comments should really be in reversed so the newest comments come first on top.

Is this tutorial still applicable today? on 16.04 ubuntu?

In this case, Wordpress Creates Infinite Redirect loop on the Homepage. Any solutions? . I just unloaded the WordPress file in DocumentRoot and installed WordPress. Now, When I try to open homepage, It shows me “Infinite redirect loop” error. . Homepage redirects itself for infinite times!

Hi Etel, nice tutorial. If I may ask what the difference is doing what you did here and doing what a colleague of your´s did here. of course here apache works in the backend while in your colleagues case its a full blown server(correct me if I am wrong), and what is the advantage if this over your method. Thanks again Etel

hello i have 000-defult not defult what i do then ? as the conf file sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/example when execute this i got the msg it not exist

Not for spamming, but I found this tutorial (howtoforge one) is more updated, and suitable than the one written in this digitalocean one. https://www.howtoforge.com/tutorial/how-to-install-nginx-as-reverse-proxy-for-apache-on-ubuntu-15-10/

How about if I use Nginx running on 443 port (https) as a proxy for Apache running on 8080 port? Will we get a notice or breakdown problem?

I was running apache and tried to install nginx and received this message:

Job for nginx.service failed because the control process exited with error code. See “systemctl status nginx.service” and “journalctl -xe” for details. invoke-rc.d: initscript nginx, action “start” failed. ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: en abled) Active: failed (Result: exit-code) since Thu 2017-11-30 23:23:19 -02; 16ms ag o Process: 3622 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code =exited, status=1/FAILURE) Process: 3616 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)

Nov 30 23:23:17 ubuntu-1gb-nyc1-01 nginx[3622]: nginx: [emerg] listen() to […) Nov 30 23:23:18 ubuntu-1gb-nyc1-01 nginx[3622]: nginx: [emerg] listen() to 0…) Nov 30 23:23:18 ubuntu-1gb-nyc1-01 nginx[3622]: nginx: [emerg] listen() to […) Nov 30 23:23:18 ubuntu-1gb-nyc1-01 nginx[3622]: nginx: [emerg] listen() to 0…) Nov 30 23:23:18 ubuntu-1gb-nyc1-01 nginx[3622]: nginx: [emerg] listen() to […) Nov 30 23:23:19 ubuntu-1gb-nyc1-01 nginx[3622]: nginx: [emerg] still could n…) Nov 30 23:23:19 ubuntu-1gb-nyc1-01 systemd[1]: nginx.service: Control proces…1 Nov 30 23:23:19 ubuntu-1gb-nyc1-01 systemd[1]: Failed to start A high perfor… Nov 30 23:23:19 ubuntu-1gb-nyc1-01 systemd[1]: nginx.service: Unit entered f… Nov 30 23:23:19 ubuntu-1gb-nyc1-01 systemd[1]: nginx.service: Failed with re… Hint: Some lines were ellipsized, use -l to show in full. dpkg: error processing package nginx-core (–configure): subprocess installed post-installation script returned error exit status 1 dpkg: dependency problems prevent configuration of nginx: nginx depends on nginx-core (>= 1.10.3-0ubuntu0.16.04.2) | nginx-full (>= 1.10. 3-0ubuntu0.16.04.2) | nginx-light (>= 1.10.3-0ubuntu0.16.04.2) | nginx-extras (> = 1.10.3-0ubuntu0.16.04.2); however: Package nginx-core is not configured yet. Package nginx-full is not installed. Package nginx-light is not installed. Package nginx-extras is not installed. nginx depends on nginx-core (<< 1.10.3-0ubuntu0.16.04.2.1~) | nginx-full (<< 1. 10.3-0ubuntu0.16.04.2.1~) | nginx-light (<< 1.10.3-0ubuntu0.16.04.2.1~) | nginx- extras (<< 1.10.3-0ubuntu0.16.04.2.1~); however: Package nginx-core is not configured yet. Package nginx-full is not installed. Package nginx-light is not installed. Package nginx-extras is not installed.

dpkg: error processing package nginx (–configure): dependency problems - leaving unconfigured Processing triggers for systemd (229-4ubuntu20) … No apport report written because the error message indicates its a followup erro r from a previous failure. Processing triggers for ureadahead (0.100.0-19) … Processing triggers for ufw (0.35-0ubuntu2) … Rules updated for profile ‘Apache Full’

Errors were encountered while processing: nginx-core nginx E: Sub-process /usr/bin/dpkg returned an error code (1)

Hey, some mod can help me? https://pastebin.com/e89BAvbW https://pastebin.com/bYBMVuXt

When I access example.com I’m been redirect to www.example.com/index.php, but I don’t want this index.php What I can do?

RewriteEngine on RewriteCond %{HTTP_HOST} ^example.com.br [NC] RewriteRule (.*) http://www.example.com.br/$1 [L,R=301]

Also, .htaccess isn’t working. What can be?

I am such a neewb to this …but can I use this method if my apache server is not using php but another cgi interpreter called livecode.? I am really banking on it. I have a working apache configuration. my plan is to combine this tutorial with what I have… hopefully it will work. great tutorial

I get as far as sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/example

When I get this error cp: cannot stat ‘/etc/apache2/sites-available/default’: No such file or directory

Hi I know this tutorial is old, but please fix the info.php test script, the first line needs to read

<?php

Or it will not get interpreted as a PHP script, and just render as a blank page.

Hello, i am curios, if on Nginx i have worker_processes = 2 and worker_connections = 1024 that means a maximum of 2048 clients, and if on Apache i have a maximum of let’s say 700 clients (i don’t know the exact value), will work with the maximum clients from Nginx and the performance?

I have a question – is this tutorial relevant for Debian 10, because it is written in 2012?

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.