301 all URLs but one with Nginx

Posted in Nginx Web Server -

There may be times you need to redirect all requests away from a domain except for a single URL, for example when redirecting all requests from http to https but leaving one file accessible under http for validation purposes. This post shows how to do this with the Nginx web server.

Nginx virtual server config

The following configuration example redirects all requests from example.com and www.example.com on port 80 to the https version of the same domain and path, except for the file 123456.txt.

You might need to do this, for example, when needing to add domain validation when setting up a secure certificate or verification when using search engines tools such as Google's Search Console (previously know as Webmaster Tools).

server {

    listen 80;
    server_name www.example.com example.com;

    location / {
        return 301 https://www.example.com$request_uri;

    location /123456.txt {
        root /path/to/webroot;


You need a root directive so Nginx knows where to find the 123456.txt file. Modify the second location (and/or add additional ones) to allow for multiple files, whole directories, etc.

Related posts: