NGinx – URL-Forwarding from a Subfolder to a new Domain

How a url forwarding works with the Apache server, I have described in this article .
However, I have now switched to Nginx, a small, sleek, and very high-performance alternative to the flagship Apache – so it better suited for a Raspberry, a Beaglebone or a Cubieboard. But NGinX has no .htaccess-files. Forwardings are there – like everything else – set in the server configuration.

So I wanted a URL forwarding from a sub-directory in which the page was before, to the new domain without transmitting the name of the subfolder. After trying some „solutions“ found in the Net, I finally got this solution working for me.
To achieve that, open the file

/etc/nginx/sites-available/default 

or the appropriate file for the virtual host or server block, as it is called in nginx.

In the simplest case it will look like this:

  server {
    server_name www.myDomain.com;
 
    root /var/www/htdocs;
  }

This server block you needs to be expanded with the following lines:

  server {
    server_name www.myDomain.com;
 
    root /var/www/htdocs;

        location /subfolder/ {
                rewrite ^/subfolder(/.*) http://www.neueDomain.de/$1 permanent; 
        } 
  }

These lines will rewrite all requests to the old address www.myDomain.de/subfolder/* to the new address http://www.neueDomain.de/*.
The switch ‚permanent‘ is for the search engines and it says that the page has permanently moved.
The search engines consider this and adapt their search results accordingly.

Schreibe einen Kommentar