Offload HTTPS traffic to Nginx only / Enginitron Cpanel
Hello, Guide which is posted on engintron.com is outdated and breaks Force SSL Functionality in Cpanel. So Here is my Solution:
Step 1. Edit /etc/apache2/conf.d/includes/pre_virtualhost_global.conf and append:
SetEnvIf X-Forwarded-Proto "https" HTTPS=on
Step 2. Run
cp /var/cpanel/templates/apache2_4/vhost.default /var/cpanel/templates/apache2_4/vhost.local
sed -i 's/RewriteCond %{HTTPS} !=on/RewriteCond %{HTTP:X-Forwarded-Proto} !https/g' /var/cpanel/templates/apache2_4/vhost.local
/scripts/rebuildhttpdconf
Step 3. Edit /etc/nginx/proxy_params_common to update proxy_pass:
proxy_pass http://$PROXY_DOMAIN_OR_IP:8080;
Step 4. restart both apache & nginx
apachectl restart systemctl restart nginx
So what are we actually doing here?
- Step 1, we are defining Apache’s behaviour when it sees the ‘X-Forwarded-Proto = https’ header. With its presence, Apache knows the traffic it is receiving is already secured with HTTPS, so it treats the request like it is https:// accordingly, even though the request is really http:// from nginx.
- Step 2, we are changing default virtualhost template to keep “Force SSL” Functionality Working and to avoid redirect loops.
- Step 2, we are telling nginx to stop sending traffic to 8443 (Apache’s https port) and instead send it to 8080 (Apache’s http port).
- Step 4, we are restarting both webservers to apply changes.
The question is, does it work? Yes, it does!
Any caveats? Glad you asked. The only I have come across is with sites using a force-rewrite to https in their .htaccess file. Typically, the code used would be:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
However, since Apache has SSL offloaded and therefore it is not handing HTTPS itself, and this activity is happening directly inside Apache (not PHP, Python, Ruby etc who are already informed about HTTPS), this code will produce a redirect loop. The solution is to use the following .htaccess code instead:
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
One more thing! This is slightly unrelated, but sysadmins do note… when using Engintron’s Nginx in front of Apache, we should remove mod_deflate from EasyApache 4. Otherwise, we will waste CPU cycles by GZIPing content twice on the web server (once on Apache, once on nginx) for no reason. This will give a very slight performance boost.
p.s: you can use grep to find sites using htaccess redirect to avoid redirect loops:
grep -rnHIi '{HTTPS}' --include=.htaccess /home
Author of original guide is : @cloudunboxed-olorinhenderson
Author of Revised version : Vasil Jamalashvili