Nginx: redirect a subdomain to a subdirectory without changing the url

We wanted these redirections:

  • => (without changing the url)
  • => (with changing the url)

In other words:

  • I wanted a subdomain that was nothing more than a page on the main site (or a subdirectory). But, the user shouldn’t know that.
  • Every link that on the subdomain should visibly redirect to the main site.

Turns out easy in Apache, but hard to accomplish with Nginx.

This is how you do it

First, create a new file in the /sites-enabled folder in your nginx installation (normally under: /etc/nginx)

Alter this:

server {
listen 8000;
root /path/to/www;

#Matches the path only (mind there is a =)
location = / {
#the rewrite statement will forward the to (which must be handled internally)
rewrite / /project;

#Matches every path (mind: there is no =)
location / {
#the rewrite statement with "permanent" at the end will visibly forward every link on the subdomain to the main domain
rewrite ^(.+)$$request_uri? permanent;
... #php handling code

The magic trick is not to use “permanent” in the rewrite statement when you don’t want it to be visible to the user. Plus mind the = signs because they mean the difference in the world for nginx configuration. More info about location can be found in the Nginx manual.

You May Also Like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.