July 20, 2012

Advanced

How To Configure Nginx as a Front End Proxy for Apache

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

Share this Tutorial

Vote on Hacker News

Try this tutorial on an SSD cloud server.

Includes 512MB RAM, 20GB SSD Disk, and 1TB Transfer for $5/mo! Learn more

Create an account or login:

125 Comments

Write Tutorial
  • Gravatar noossa over 1 year

    Very, very good!

  • Gravatar dperson2010 over 1 year

    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?

  • Gravatar Moisey over 1 year

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

  • Gravatar Etel Sverdlov over 1 year

    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.

  • Gravatar jason over 1 year

    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?

  • Gravatar Etel Sverdlov over 1 year

    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!

  • Gravatar jessehaung over 1 year

    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?

  • Gravatar Jeff Carr over 1 year

    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).

  • Gravatar Moisey over 1 year

    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.

  • Gravatar casias.adge over 1 year

    This worked perfectly. Thank You!

  • Gravatar casias.adge over 1 year

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

  • Gravatar Moisey over 1 year

    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.

  • Gravatar chinmoybad over 1 year

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

  • Gravatar Moisey over 1 year

    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. =]

  • Gravatar Moisey over 1 year

    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.

  • Gravatar casias.adge over 1 year

    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?

  • Gravatar markangelo7777 about 1 year

    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!

  • Gravatar ajob367 about 1 year

    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?

  • Gravatar Samuel Jacques about 1 year

    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

  • Gravatar Etel Sverdlov about 1 year

    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.

  • Gravatar Samuel Jacques about 1 year

    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 ?

  • Gravatar paassalles about 1 year

    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

  • Gravatar jmarston4 about 1 year

    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.

  • Gravatar Chris Bunting about 1 year

    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/

  • Gravatar anhsang9x about 1 year

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

  • Gravatar Ryan W KAN about 1 year

    I followed the directions and installed my wordpress, but ended up with a redirect loop error. The wp-admin page loads fine. Any idea?

  • Gravatar Peter about 1 year

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

  • Gravatar supirole 12 months

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

  • Gravatar Svetoslav Marinov (SLAVI) 11 months

    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.

  • Gravatar Prasenjit 11 months

    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.

  • Gravatar Kamal Nasser 11 months

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

  • Gravatar witolot 10 months

    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

  • Gravatar Kamal Nasser 10 months

    Did you configure apache to listen on port 8080?

  • Gravatar witolot 10 months

    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).

  • Gravatar Kamal Nasser 10 months

    > 2) 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)

  • Gravatar witolot 10 months

    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.

  • Gravatar Kamal Nasser 10 months

    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.

  • Gravatar witolot 10 months

    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! :)

  • Gravatar witolot 10 months

    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!

  • Gravatar Kamal Nasser 10 months

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

  • Gravatar rene.peter18 10 months

    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.

  • Gravatar witolot 10 months

    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!

  • Gravatar rene.peter18 10 months

    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

  • Gravatar Kamal Nasser 10 months

    @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.

  • Gravatar Felix Fennell 10 months

    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 :)

  • Gravatar Kamal Nasser 10 months

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

  • Gravatar proxyland 9 months

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

  • Gravatar Kamal Nasser 9 months

    @proxyland: Yes. :]

  • Gravatar rjpitt 9 months

    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!

  • Gravatar Kamal Nasser 9 months

    @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).

  • Gravatar the8thsite 9 months

    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

  • Gravatar Kamal Nasser 9 months

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

  • Gravatar skyaccessorg 8 months

    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

  • Gravatar Kamal Nasser 8 months

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

  • Gravatar skyaccessorg 8 months

    There are a few other .htaccess files in the directories but this is the one in the main /var/www http://pastebin.com/6KmZU9j9

  • Gravatar skyaccessorg 8 months

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

  • Gravatar Kamal Nasser 8 months

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

  • Gravatar skyaccessorg 8 months

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

  • Gravatar Kamal Nasser 8 months

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

  • Gravatar skyaccessorg 8 months

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

  • Gravatar Kamal Nasser 8 months

    @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

  • Gravatar david 8 months

    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; } }

  • Gravatar Kamal Nasser 8 months

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

  • Gravatar david 8 months

    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!

  • Gravatar Kamal Nasser 8 months

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

  • Gravatar sobrelaweb 8 months

    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!

  • Gravatar Kamal Nasser 8 months

    @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.

  • Gravatar sobrelaweb 8 months

    @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: RedirectPermanent / https://www.verifybtc.com/ ....SSL conf Now I changed it to: Normal conf 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.

  • Gravatar Kamal Nasser 8 months

    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:

    server {
        listen 80;
        server_name www.yourdomain.com yourdomain.com;
    
        rewrite ^(.*)$ https://yourdomain.com$1 permanent;
    }

  • Gravatar sobrelaweb 8 months

    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!

  • Gravatar Kamal Nasser 8 months

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

    rewrite ^/panel /index.php?page=panel;

  • Gravatar sobrelaweb 8 months

    Thanks again, finally it worked on the 443 config!

  • Gravatar Kamal Nasser 8 months

    Sweet! :]

  • Gravatar lanjunq 8 months

    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?

  • Gravatar Kamal Nasser 8 months

    @lanjunq: Check nginx's and apache's error logs -- do you see anything?

  • Gravatar stmeter 8 months

    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.

  • Gravatar stmeter 8 months

    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 :)

  • Gravatar Kamal Nasser 7 months

    @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?

  • Gravatar ninthfact 7 months

    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 ??

  • Gravatar ninthfact 7 months

    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 ??

  • Gravatar Kamal Nasser 7 months

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

  • Gravatar mas 7 months

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

  • Gravatar Kamal Nasser 7 months

    @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.

  • Gravatar hotro 7 months

    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 ?

  • Gravatar Kamal Nasser 7 months

    @hotro: Does /home/mywebsite.com/public_html/images/1.png exist? Please pastebin apache and nginx's config on pastebin.com or a similar service.

  • Gravatar hotro 7 months

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

  • Gravatar lippiltv 6 months

    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

  • Gravatar gmqqueen 6 months

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

  • Gravatar Kamal Nasser 6 months

    @gmqqueen: Both, see: - https://www.digitalocean.com/community/articles/how-to-set-up-apache-virtual-hosts-on-ubuntu-12-04-lts - https://www.digitalocean.com/community/articles/how-to-set-up-nginx-virtual-hosts-server-blocks-on-ubuntu-12-04-lts--3

  • Gravatar bd 6 months

    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

  • Gravatar Kamal Nasser 6 months

    @bd: The easiest way to redirect www. to non-www is creating a separate nginx virtualhost: https://p.kk7.me/cukicomohi.nginx

  • Gravatar Kamal Nasser 6 months

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

  • Gravatar xpbazsi 6 months

    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

  • Gravatar xpbazsi 6 months

    I hope it helps a lot ;))

  • Gravatar Santiago 6 months

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

  • Gravatar h3r0k0 6 months

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

  • Gravatar Kamal Nasser 6 months

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

  • Gravatar Xchanger 6 months

    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 !!!

  • Gravatar Kamal Nasser 6 months

    @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 not editing any config files manually/installing packages which would probably break Froxlor.

  • Gravatar mobin.kurien.web 6 months

    i have followed the intructions but i ned up with on my web page instead of the php information page

  • Gravatar Kamal Nasser 6 months

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

  • Gravatar henriquesacramento 5 months

    how to use this with varnish ?

  • Gravatar Kamal Nasser 5 months

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

  • Gravatar a.krivtcun 5 months

    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.

  • Gravatar grigorym 5 months

    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.

  • Gravatar ryan.burnette 4 months

    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?

  • Gravatar Kamal Nasser 4 months

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

  • Gravatar larry 3 months

    I am able to proxy from nginx to apache EXCEPT if I try to use SEO friendly urls /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: /en/?____icl_validate_domain=1 This is the relevant .htaccess: # BEGIN WordPress RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END WordPress Thank you for any observations. :)

  • Gravatar larry 3 months

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

  • Gravatar larrypack about 1 month

    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?

  • Gravatar Kamal Nasser about 1 month

    @larrypack: Can you pastebin your nginx config?

  • Gravatar roman about 1 month

    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 ... ServerAdmin [email protected] DocumentRoot /srv/www/mysite.com/public_html/ ServerName mysite.com ErrorLog logs/mysite.com-error_log CustomLog logs/mysite.com-access_log common Options All AllowOverride All Allow from all

  • Gravatar larrypack about 1 month

    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?

  • Gravatar larrypack about 1 month

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

  • Gravatar FMCB about 1 month

    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?

  • Gravatar Kamal Nasser about 1 month

    @FMCB: In that case it's recommended to just go with nginx and completely ditch Apache. Check out https://www.digitalocean.com/community/articles/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-12-04 To host two different sites, you will need to create a new virtualhost for each new site: https://www.digitalocean.com/community/articles/how-to-set-up-nginx-virtual-hosts-server-blocks-on-ubuntu-12-04-lts--3.

  • Gravatar FMCB about 1 month

    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

  • Gravatar Kamal Nasser about 1 month

    @FMCB:

    In such case Apache is the only web server that can handle multiple connections with heavy load traffic.
    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).

  • Gravatar FMCB about 1 month

    Thanks @Kamal for correcting me. I will test both Nginx + php-fpm and Nginx reverse proxy at front end Apache. Regards,

  • Gravatar muszek 19 days

    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

  • Gravatar muszek 18 days

    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).

  • Gravatar muszek 18 days

    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.

  • Gravatar arul.smartpixels 15 days

    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 .

  • Gravatar Kamal Nasser 15 days

    @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?

  • Gravatar angelo.corbo 9 days

    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

Leave a Comment

Create an account or login:
Ajax-loader