Nginx: redirect a subdomain to a subdirectory without changing the url - developed.be

  • Published:November 4th, 2013
  • Category:nginx

We wanted these redirections:

  • project.example.com => www.example.com/project (without changing the url)
  • project.example.com/whatever => www.example.com/whatever (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;
  server_name project.example.com;
  root   /path/to/www;
 
  #Matches the path project.example.com only (mind there is a =)
  location = / {
    #the rewrite statement will forward the project.example.com to project.example.com/project (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 ^(.+)$ http://www.example.be$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.


Rss Comments

Comments

No comments yet.

Leave a comment