cPanel: Setup Nginx as Reverse Proxy with Apache

cPanel comes with Apache web server by default. Its not mean that we cannot integrated Nginx inside. With some minor changes, we can install Nginx to listen to port 80 and forward any PHP process to Apache on another port, 88. Apache is not really good in handling static files, so we will pass this task to Nginx. You will noticed that your memory and CPU will decrease once you have done this setup.

Warning: This setting is not suitable for shared hosting environment. I strongly recommend you to apply this if you have 1 busy website running under cPanel. Make sure you have compiled your Apache modules and features using EasyApache.

I am using variables as below:

OS: CentOS 5.6 32bit
cPanel: cPanel 11.30.1 (build 4)
Domain IP: 123.124.125.88
Apache port: 88
Domain: mywebs.net
User: mywebs
Home directory: /home/mywebs

1. Since Nginx will be reverse proxy for Apache, we don’t want our log file to record the proxy IP. We want the real IP as usual. This will make sure our stats page like Webalizer and AWstats will record the correct information. So we need to install mod_rpaf which is “Reverse Proxy Add Forward” module for Apache. You can download that at http://stderr.net/apache/rpaf/download:

cd /usr/local/src
wget http://stderr.net/apache/rpaf/download/mod_rpaf-0.6.tar.gz
tar -xzf mod_rpaf-0.6.tar.gz
cd mod_rpaf-*
apxs -i -c -n mod_rpaf-2.0.so mod_rpaf-2.0.c

2. Once installed, we need to load the module into Apache configuration. Since cPanel already has Include Editor for Apache, we will use that functions. Login to WHM > Service Configuration > Apache Configuration > Include Editor > Pre Main Include > All Versions and paste following text:

LoadModule rpaf_module modules/mod_rpaf-2.0.so
RPAFenable On
RPAFproxy_ips 127.0.0.1  123.124.125.88 # replace the value with your server IP
RPAFsethostname On
RPAFheader X-Real-IP

3. Click Update > Restart Apache. The module should be loaded after restart.

4. Before we install Nginx, we need to change Apache port to 88. Login to WHM > Server Configuration > Tweak Settings > Apache non-SSL IP/port:

0.0.0.0:88

5. We need to run following command so cPanel will remember that Apache configuration template has changed:

/usr/local/cpanel/bin/apache_conf_distiller --update --main
/scripts/rebuildhttpdconf

6. Lets install Nginx and all requirements using yum. You can download Nginx source at http://nginx.org/en/download.html:

yum install pcre* -y
cd /usr/local/src
wget http://nginx.org/download/nginx-1.0.5.tar.gz
cd nginx-*
./configure
make
make install

7. Once installed, we need to do some changes to Nginx configuration file. Using text editor, copy and paste following line and change the required value to fit your environment:

user  nobody;
worker_processes  1;
 
error_log  logs/error.log  info;
 
events {
    worker_connections  1024;
}
 
http {
    server_names_hash_max_size 2048;
    include       mime.types;
    default_type  application/octet-stream;
 
    log_format   main '$remote_addr - $remote_user [$time_local]  $status '
    '"$request" $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';
 
    sendfile        on;
    tcp_nopush     on;
 
    keepalive_timeout  10;
 
    gzip  on;
    gzip_min_length  1100;
    gzip_buffers  4 32k;
    gzip_types    text/plain application/x-javascript text/xml text/css;
    ignore_invalid_headers on;
 
    client_header_timeout  3m;
    client_body_timeout 3m;
    send_timeout     3m;
    connection_pool_size  256;
    client_header_buffer_size 4k;
    large_client_header_buffers 4 32k;
    request_pool_size  4k;
    output_buffers   4 32k;
    postpone_output  1460;
 
 server {
  # this is your access logs location
  access_log /usr/local/apache/domlogs/mywebs/mywebs.net;
 
  error_log  logs/vhost-error_log warn;
  listen    80;
  # change to your domain
  server_name  mywebs.net www.mywebs.net;
 
  location ~* \.(gif|jpg|jpeg|png|wmv|avi|mpg|mpeg|mp4|htm|html|js|css)$ {
   # this is your public_html directory
   root   /home/mywebs/public_html;
  }
 
  location / {
   client_max_body_size    10m;
   client_body_buffer_size 128k;
 
   proxy_send_timeout   90;
   proxy_read_timeout   90;
 
   proxy_buffer_size    4k;
   proxy_buffers     16 32k;
   proxy_busy_buffers_size 64k;
   proxy_temp_file_write_size 64k;
 
   proxy_connect_timeout 30s;
 
   # change to your domain name
   proxy_redirect  http://www.mywebs.net:88   http://www.mywebs.net;
   proxy_redirect  http://mywebs.net:88   http://mywebs.net;
 
   proxy_pass   http://127.0.0.1:88/;
   proxy_set_header   Host   $host;
   proxy_set_header   X-Real-IP  $remote_addr;
   proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
  }
 }
}

8. We need to check the Nginx configuration file before start the Nginx. Use following command to check the configuration file:

[email protected] [~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

9. If everything is OK, we can start the Nginx as below:

/usr/local/nginx/sbin/nginx

10. Lets check whether Nginx and Apache are listening to the correct port:

[email protected] [~]# netstat -tulpn | grep -e nginx -e httpd
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      16728/nginx
tcp        0      0 0.0.0.0:88                  0.0.0.0:*                   LISTEN      19655/httpd
tcp        0      0 0.0.0.0:443                 0.0.0.0:*                   LISTEN      19655/httpd

11. Browse your website. You should notice that your server header has changed from Apache to Nginx. You can check your website’s server header at http://www.seoconsultants.com/tools/headers.

12. If everything is run as expected, edit /etc/rc.local using text editor and add following line so Nginx will start automatically after reboot

/usr/local/nginx/sbin/nginx

Nginx no need to be restarted to load the latest configuration file. You can run following command and it will reload the configuration on-the-fly without downtime:

kill -HUP `ps -ef | grep nginx | grep master | awk {'print $2'}`

Done. Let me know if you encounter any problem during the process. Cheers!

24 thoughts on “cPanel: Setup Nginx as Reverse Proxy with Apache

  1. Going to attempt to put this on my VPS. But have a question..

    I have several cPanels on my VPS. For the “Nginx configuration file” do I just put the primary domain that’s tied to the VPS. My worry if I put in a domain in the “Nginx configuration file” then my other domains won’t load? Or am I just being paranoid?

    Thanks for this tutorial. I’m at step 4 and I’m worried to go further until I know for certain it will work.

    Reply

    1. This post is explaining on how to setup ONE domain (which is in the list of your cPanel ‘List Account’) run on nginx. If you have many domains inside, there are 2 options:
      1. You need to add the “server” directive (line 40 onwards) in nginx config file for every domain inside your cPanel
      2. If you choose only one domain to be hosted using nginx in port 80, your other domains (which not in nginx config file) are accessible via port 88. so you might need to access them at http://mywebs.net:88

      Reply

  2. Is there a reason why you mention a older version of nginx in your post. Is it more stable or should I use the latest version?

    Also how would I easily revert to just Apache in case I screw things up?

    Reply

    1. During this write up, that is the latest version of Nginx available. Actually it is recommended to use latest stable version.

      If things screw up or you want to revert to old setup with Apache:
      1. kill all nginx processes currently running
      2. remove added lines in step 2,
      3. change 0.0.0.0:88 to 0.0.0.0:80 in step 4
      4. do step 5
      5. do step 10 to verify whether Apache has taken back port 80 to serve website

      Good luck!

      Reply

  3. i just follow all of steps , and even all the test successful but when i browzer the site , its show me , the page welcome to nginx! How can i reslove this issue , its on my forum main page ,

    Reply

    1. Make sure you map your website domain to the respective IP:
      For example: desicornet.net is resolved to 46.102.247.99. So all value inside nginx configuration file must be using this IP and this domain.

      Usually when you see nginx welcome page, is because nginx cannot determine which IP and http header that match inside the configuration file. As a result, nginx do not know which virtual host to refer to so they open the default landing page instead of your website page.

      Reply

  4. I have update this post on step no 7. u may try it once again. dont forget to allow firewall on port 88 as well

    Reply

  5. hllo,

    i have installed this successfully and working, but other domains on server not working, infact sites loading without images

    Reply

    1. In this tutorial, i have warned that this setup is only for one domain and not shared hosting environment. If you want to have other domain to be hosted as well, you need to generate the server directive in nginx configuration files. Copy line 40 until the end and paste again for your other domain. Example:

      line 40……
      server {
      domain A configurations
      }
      server {
      domain B configurations
      }
      and so on…

      Reply

  6. To open port 88 in your firewall:

    If you are using APF, add port 88 into /etc/apf/conf.apf

    If you are using IPtables, run following command:
    $ iptables -A INPUT -p tcp -m tcp –dport 88 -j ACCEPT
    $ service iptables save
    $ service iptables restart

    Your configuration seems correct from my point-of-view. Kindly try again

    Reply

  7. hello, thanks. the above config file Fassy shared i am using same, please can you edit that for 2 domains, so i will understand easily

    Reply

    1. Yes, it should be correct. Guys, be reminded to not show your sensitive information like configuration content in this blog. People can take advantage by knowing your server configuration files. I am suggesting you to email me by using contact form or directly at seca @ email.com. I would be happy to help via that channel as well

      Reply

  8. Tnx for tutorial, all work ok…but my permalinks (url rewrite) on wordpress sites not work…I just have my home page 🙁 any suggestion?

    Reply

  9. Tnx for tutorial.
    I am a beginner in linux and I wonder if there is any possibility of a problem arises with WHM / Cpanel when installing the pcre dependency? and if there is a problem using the latest version of nginx 1.0.12 stable?

    Reply

    1. The problem might arise if you are using another cPanel-PCRE depended software like APC and some mod_security rules. In this case, cPanel will use its own PCRE build and will surely bring dependency problem depending on what cPanel update (stable,latest,current) version you choose.

      Reply

  10. How to change the server header to any other statement like “Secured Server !”

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *