Vesta Control Panel - Forum

Community Forum

Skip to content

Advanced search
  • Quick links
    • Main site
    • Github repo
    • Google Search
  • FAQ
  • Login
  • Register
  • Board index Main Section Web Server
  • Search

How to redirect the subdomain mobile version (mobile.example.com) of your website using nginx

Questions regarding the Web Server
Apache + Nginx, Nginx + PHP5-FPM
Post Reply
  • Print view
Advanced search
1 post • Page 1 of 1
King Soja
Posts: 2
Joined: Tue Nov 17, 2020 7:09 pm

Os: CentOS 7x
Web: nginx + php-fpm
How to redirect the subdomain mobile version (mobile.example.com) of your website using nginx
  • Quote

Post by King Soja » Tue Dec 08, 2020 2:57 pm

Hello,
I would very much appreciate any help or solution. Many thanks in advance.
OS: CentOS 7 x86 minimal
Webserver: Nginx version: 1.18.0
Website: Wordpress
Please Note: I have omitted the actual name of my website for obvious reasons.

1. I created a subdomain : mobile.example.com successfully in Vesta CP.

2. I pointed mobile.example.com to the document root of www.example.com

3. The www.example.com has two nginx files in Vesta setup for all the redirections from http to https, non-www to www. In other words, one for non-ssl/http, and the other for ssl/https redirections. (Please: kindly check below for the details for all the files)

4. The mobile.example.com also has two nginx files in Vesta setup for all the redirections from http to https, non-www to www. In other words, one for non-ssl/http, and the other for ssl/https redirections. (Please: kindly check below for the details for all the files)

4. I added this code for the mobile redirection in the nginx ssl/https file for www.example.com:

Code: Select all

#----- redirect to mobile check (starts) -----#
	set $mobile_rewrite do_not_perform;
	
	if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino") {
      set $mobile_rewrite perform;
    }
	
	if ($http_user_agent ~* "^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-)") {
      set $mobile_rewrite perform;
    }
	
	if ($mobile_rewrite = perform) {
      rewrite ^ https://mobile.example.com$request_uri? redirect;
      break;
    }
	#----- redirect to mobile check (ends) -----#
5. However, when I do the above setup for a new Wordpress installation, it works perfectly but when I use same for an old Wordpress site or a back-up Wordpress installation the message I get is:
404 Page Not Found. The page you requested was not found

6. I'm more grateful and thankful in advance. Many, many thanks.

Here are all the details of the Nginx files for both www.example.com & mobile.example.com.


1. nginx.conf file for the non-ssl or http:www.example.com version:

Code: Select all

server {
    listen      000.000.000.000:80;
    server_name example.com www.example.com;
    root        /home/admin/web/example.com/public_html;
    index       index.php index.html index.htm;
    access_log  /var/log/nginx/domains/example.com.log combined;
    access_log  /var/log/nginx/domains/example.com.bytes bytes;
    error_log   /var/log/nginx/domains/example.com.error.log error;

    location / {

        location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
            expires     max;
			fastcgi_hide_header "Set-Cookie";
        }

        location ~ [^/]\.php(/|$) {
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            if (!-f $document_root$fastcgi_script_name) {
                return  404;
            }

            fastcgi_pass    unix:/run/php-fpm/www.sock;
            fastcgi_index   index.php;
            include         /etc/nginx/fastcgi_params;
        }
    }

    error_page  403 /error/404.html;
    error_page  404 /error/404.html;
    error_page  500 502 503 504 /error/50x.html;

    location /error/ {
        alias   /home/admin/web/example.com/document_errors/;
    }

    location ~* "/\.(htaccess|htpasswd)$" {
        deny    all;
        return  404;
    }

    location /vstats/ {
        alias   /home/admin/web/example.com/stats/;
        include /home/admin/conf/web/example.com.auth*;
    }

    include     /etc/nginx/conf.d/phpmyadmin.inc*;
    include     /etc/nginx/conf.d/phppgadmin.inc*;
    include     /etc/nginx/conf.d/webmail.inc*;

    include     /home/admin/conf/web/nginx.example.com.conf*;
}
2. nginx.conf file for the ssl or https:www.example.com version:

Code: Select all

# Redirect NON WWW -> WWW  ===  This server block will redirect https://mysite.com to https://www.mysite.com (expecting that you have a certificate for mysite.com as well as www.mysite.com
server {
    listen 000.000.000.000:443 ssl http2;
	listen [::]:443 ssl http2;
    server_name example.com;

    ssl_certificate      /home/admin/conf/web/ssl.example.com.pem;
    ssl_certificate_key  /home/admin/conf/web/ssl.example.com.key;
	
    return 301 https://www.example.com$request_uri;
}

# This is the server block actually delivering content to the visitor
server {
    listen 000.000.000.000:443 ssl http2;
	listen [::]:443 ssl http2;
    server_name www.example.com;
    
	root        /home/admin/web/example.com/public_html;
    index       index.php index.html index.htm;
    access_log  /var/log/nginx/domains/example.com.log combined;
    access_log  /var/log/nginx/domains/example.com.bytes bytes;
    error_log   /var/log/nginx/domains/example.com.error.log error;

    # SSL parameters
    ssl_certificate      /home/admin/conf/web/ssl.example.com.pem;
    ssl_certificate_key  /home/admin/conf/web/ssl.example.com.key;
	
	ssl_client_certificate /etc/pki/tls/certs/ca-bundle.crt;
	
	ssl_stapling on; # managed by Certbot
    ssl_stapling_verify on; # managed by Certbot

    ssl_session_cache shared:SSL:10m;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers "ECDHE-RSA-AES256-SHA384:AES256-SHA256:AES256-SHA256:RC4:HIGH:MEDIUM:+TLSv1:+TLSv1.1:+TLSv1.2:!MD5:!ADH:!aNULL:!eNULL:!NULL:!DH:!ADH:!EDH:!AESGCM";
	
    add_header Content-Security-Policy "frame-ancestors https://www.example.com/;";
	add_header Referrer-Policy 'strict-origin';
	add_header Feature-Policy "vibrate none; geolocation none; unsized-media https://www.example.com;";
	add_header "Access-Control-Allow-Origin" $http_origin;
	
	add_header X-Xss-Protection "1; mode=block" always;
	
	include     /home/admin/web/example.com/public_html/nginx.conf;
	include     /etc/nginx/conf.d/phpmyadmin.inc*;
    include     /etc/nginx/conf.d/phppgadmin.inc*;
    include     /etc/nginx/conf.d/webmail.inc*;
    include     /home/admin/conf/web/snginx.example.com.conf*;
	
    location  /.well-known/acme-challenge/ {
            allow all;
    }

    location = ^/favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = ^/robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }
	
	# Deny access to uploads that aren’t images, videos, music, etc.
    location ~* ^/wp-content/uploads/.*.(html|htm|shtml|php|js|swf)$ {
        access_log off;
		log_not_found off;
		deny all;
    }
	
	# Deny public access to wp-config.php
    location ~* wp-config.php {
        deny all;
    }
	
	# serve png, jpg, jpeg as Webp Next Gen images if available
    location ~* ^.+\.(png|jpe?g)$ {
        add_header Vary Accept;
        try_files $uri$webp_suffix $uri =404;
    }
	
	location /error/ {
        alias   /home/admin/web/example.com/document_errors/;
    }

    location /vstats/ {
        alias   /home/admin/web/example.com/stats/;
        include /home/admin/conf/web/example.com.auth*;
    }
	
	location / {
        try_files $uri $uri/ /index.php?$args;
    }
	
	#----- redirect to mobile check (starts) -----#
	set $mobile_rewrite do_not_perform;
	
	if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino") {
      set $mobile_rewrite perform;
    }
	
	if ($http_user_agent ~* "^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-)") {
      set $mobile_rewrite perform;
    }
	
	if ($mobile_rewrite = perform) {
      rewrite ^ https://mobile.example.com$request_uri? redirect;
      break;
    }
	#----- redirect to mobile check (ends) -----#
	
    # REQUIREMENTS : Enable PHP Support
	location ~ \.php$ {
        fastcgi_param GATEWAY_INTERFACE CGI/1.1;
		fastcgi_param SERVER_SOFTWARE nginx;
		fastcgi_param QUERY_STRING $query_string;
		fastcgi_param REQUEST_METHOD $request_method;
		fastcgi_param CONTENT_TYPE $content_type;
		fastcgi_param CONTENT_LENGTH $content_length;
		fastcgi_param SCRIPT_FILENAME /home/admin/web/example.com/public_html$fastcgi_script_name;
		fastcgi_param SCRIPT_NAME $fastcgi_script_name;
		fastcgi_param REQUEST_URI $request_uri;
		fastcgi_param DOCUMENT_URI $document_uri;
		fastcgi_param DOCUMENT_ROOT /home/admin/web/example.com/public_html;
		fastcgi_param SERVER_PROTOCOL $server_protocol;
		fastcgi_param REMOTE_ADDR $remote_addr;
		fastcgi_param REMOTE_PORT $remote_port;
		fastcgi_param SERVER_ADDR $server_addr;
		fastcgi_param SERVER_PORT $server_port;
		fastcgi_param SERVER_NAME $server_name;
		fastcgi_param HTTPS $https;
		location ~ \.php$ {
			try_files $uri =404;
			fastcgi_pass unix:/run/php-fpm/www.sock;
	    }
	error_page  403 /error/404.html;
    error_page  404 /error/404.html;
    error_page  500 502 503 504 /error/50x.html;
	
	# PERFORMANCE : Media: images, icons, video, audio, HTC Set expires headers for static files and turn off logging
	location ~* .(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
        expires 90d;
		add_header Cache-Control "public, no-transform";
    }
	
	location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
        expires     max;
        fastcgi_hide_header "Set-Cookie";
    }
	
	#location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|svg)$ {
    #   expires 365d;
    #}
    
	location ~* \.(pdf|html|swf)$ {
    expires 90d;
    }
	
	# PLUGINS : Enable Rewrite Rules for Yoast SEO SiteMap
    rewrite ^/sitemap_index\.xml$ /index.php?sitemap=1 last;
    rewrite ^/([^/]+?)-sitemap([0-9]+)?\.xml$ /index.php?sitemap=$1&sitemap_n=$2 last;
	
	# Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
    # Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)
    location ~ /\. {
        deny all;
    }
	
	# SECURITY : Deny all attempts to access PHP Files in the uploads directory
    location ~* /(?:uploads|files)/.*\.php$ {
        deny all;
    }
	
	#W3 TOTAL CACHE CHECK 
    set $cache_uri $request_uri;

    # POST requests and urls with a query string should always go to PHP
    if ($request_method = POST) {
        set $cache_uri 'null cache';
    }   
    if ($query_string != "") {
        set $cache_uri 'null cache';
    }   

    # Don't cache uris containing the following segments
    if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
        set $cache_uri 'null cache';
    }   

    # Don't use the cache for logged in users or recent commenters
    if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in") {
        set $cache_uri 'null cache';
    }
}

}
1. nginx.conf file for the non-ssl or http:mobile.example.com version:

Code: Select all

server {
    listen      000.000.000.000:80;
    server_name mobile.example.com www.mobile.example.com;
    root        /home/admin/web/example.com/public_html;
    index       index.php index.html index.htm;
    access_log  /var/log/nginx/domains/mobile.example.com.log combined;
    access_log  /var/log/nginx/domains/mobile.example.com.bytes bytes;
    error_log   /var/log/nginx/domains/mobile.example.com.error.log error;

    location / {

        location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
            expires     max;
			fastcgi_hide_header "Set-Cookie";
        }

        location ~ [^/]\.php(/|$) {
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            if (!-f $document_root$fastcgi_script_name) {
                return  404;
            }

            fastcgi_pass    unix:/run/php-fpm/www.sock;
            fastcgi_index   index.php;
            include         /etc/nginx/fastcgi_params;
        }
    }

    error_page  403 /error/404.html;
    error_page  404 /error/404.html;
    error_page  500 502 503 504 /error/50x.html;

    location /error/ {
        alias   /home/admin/web/mobile.example.com/document_errors/;
    }

    location ~* "/\.(htaccess|htpasswd)$" {
        deny    all;
        return  404;
    }

    location /vstats/ {
        alias   /home/admin/web/mobile.example.com/stats/;
        include /home/admin/conf/web/mobile.example.com.auth*;
    }

    include     /etc/nginx/conf.d/phpmyadmin.inc*;
    include     /etc/nginx/conf.d/phppgadmin.inc*;
    include     /etc/nginx/conf.d/webmail.inc*;

    include     /home/admin/conf/web/nginx.mobile.example.com.conf*;
}
1. nginx.conf file for the ssl or https:mobile.example.com version:

Code: Select all

server {
    listen      000.000.000.000:443;
    server_name mobile.example.com www.mobile.example.com;
    root        /home/admin/web/example.com/public_html;
    index       index.php index.html index.htm;
    access_log  /var/log/nginx/domains/mobile.example.com.log combined;
    access_log  /var/log/nginx/domains/mobile.example.com.bytes bytes;
    error_log   /var/log/nginx/domains/mobile.example.com.error.log error;

    ssl_certificate      /home/admin/conf/web/ssl.mobile.example.com.pem;
    ssl_certificate_key  /home/admin/conf/web/ssl.mobile.example.com.key;

    location / {

        location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
            expires     max;
        }

        location ~ [^/]\.php(/|$) {
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            if (!-f $document_root$fastcgi_script_name) {
                return  404;
            }

            fastcgi_pass    unix:/run/php-fpm/www.sock;
            fastcgi_index   index.php;
            include         /etc/nginx/fastcgi_params;
        }
    }

    error_page  403 /error/404.html;
    error_page  404 /error/404.html;
    error_page  500 502 503 504 /error/50x.html;

    location /error/ {
        alias   /home/admin/web/mobile.example.com/document_errors/;
    }

    location ~* "/\.(htaccess|htpasswd)$" {
        deny    all;
        return  404;
    }

    location /vstats/ {
        alias   /home/admin/web/mobile.example.com/stats/;
        include /home/admin/conf/web/mobile.example.com.auth*;
    }

    include     /etc/nginx/conf.d/phpmyadmin.inc*;
    include     /etc/nginx/conf.d/phppgadmin.inc*;
    include     /etc/nginx/conf.d/webmail.inc*;

    include     /home/admin/conf/web/snginx.mobile.example.com.conf*;
}
Many, many thanks once more!
Top


Post Reply
  • Print view
1 post • Page 1 of 1

Return to “Web Server”



  • Board index
  • All times are UTC
  • Delete all board cookies
  • The team
Powered by phpBB® Forum Software © phpBB Limited
*Original Author: Brad Veryard
*Updated to 3.2 by MannixMD
 

 

Login  •  Register

I forgot my password