[Drupal] How to use Nginx redirect for Drupal websites

| | 2 min read

If you are a Nginx web server user and using Drupal as your CMS, it is quite different for redirects. Imagine that you have two websites, so if we change from an old site to a new site some of the URL will return 'Page not found'. So for that reason we can redirect them to the correct URL. If you are also looking for a 301 redirect for your Drupal site please read on.

To load a single page in Drupal it requires full Drupal Bootstrap. So create a module and fix the very few 'Page not found' issues since it is not good from the performance point of view. For that we need something which should work before Drupal Bootstrap handles these URLs.
But if you have huge amount of URL in your site which throws 404 error then you may need to create a custom module to fix it.

First thing you have to do is get both the URLs. That means URL which throws 404 and URL that you want to redirect. Then go to your Nginx.conf file. It will be located at /etc/Nginx/Nginx.conf. Now edit your ngix.conf

sudo vim /etc/nginx/nginx.conf

See the example below,

server {
  # Rest of config
  rewrite  ^/old/url$ http://host/new/url permanent;
  # Rest of config.
}

The syntax for Nginx rewrite rule is:

rewrite regex replacement [ flag ];

Flags can be any of the following:

  • last: This completes processing of current rewrite directives and restarts the process (including rewriting) with a search for a match on the URI from all available locations.
  • break: This completes processing of current rewrite directives and non-rewrite processing continues within the current location block only.
  • redirect: This returns temporary redirect with code 302
  • permanent: This returns permanent redirect with code 301

Hope the content is helpful, you can check other information for Nginx and Drupal.

Reference: More on Flags