nginx redirect or return single location

jwir3 asked:

I am trying to get videos.mydomain.com/kickboxing to redirect to a YouTube link, as well as videos.mydomain.com/classes to redirect to a different YouTube link. (These are both unlisted playlists, and I want anyone who has access to our website to have this redirect happen automatically for them. This is step 1 of several steps of configuring this and I can’t seem to get it to work).

Here’s my configuration:

server {
  server_name videos.mydomain.com;
  root /var/www/www.mydomain.com;

  listen 80;
  access_log /var/log/nginx/videos.mydomain.com-access.log;
  error_log /var/log/nginx/videos.mydomain.com-error.log debug;

  location /classes {
    return 301 https://youtube.com/playlist?list=classes-playlist;
  }

  location /kickboxing {
    return 301 https://youtube.com/playlist?list=kickboxing-playlist;
  }

  return 404;
}

I’ve set this up in my sites-available, as well as enabled it (and of course, set up DNS). Unfortunately, when I navigate to the urls http://videos.mydomain.com/kickboxing or http://videos.mydomain.com/classes, all I get is the 404 url. If I change the return 404 line to one of the return 301 lines, then it will redirect appropriately, but only for that particular url. It seems to not be correctly identifying the location sections.

My answer:


This happens because you put return 404; in the server block.

Rewrites at the server level are processed before rewrites at the location level.

To fix the problem, put it in a location. (As a general rule you should always process requests in a location.)

    location / {
        return 404;
    }

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.