Rewrite on root of domain only in nginx

I've got YOURLS server running to host short urls for my company, so that we can provide short URL's to our customers.

I'm using nginx, and for root of the domain, if they aren't using a proper short url I want to redirect to our website. So example.com/218a redirects to whatever that short url points to, but example.com goes to our site @ domain.com.

Right now, I'm using an index.html page with just a meta refresh to redirect, but I was thinking I should be able to do that in the nginx config and it would likely be better.

Can someone help me with the proper way, if it's possible, to make that happen at the server level instead of using meta refresh?

I've tried a few examples on that I found here, but none of them seem to work.

Here is my config file for reference.

server {
    server_name www.domain.com;
    return 301 $scheme://domain.com$request_uri;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.html index.htm index.php;

    # Make site accessible from http://localhost/
    server_name http://domain.com;

    location / {
        #YOURLS
        try_files $uri $uri/ /yourls-loader.php;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass php5-fpm-sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors on;
    }
}

Solution 1:

First of all, the server_name directive is invalid in your main server block. server_name contains only the domain name, not any other parts of the URL.

To answer your actual question, add the following configuration:

location = / {
    rewrite ^ http://domain.com permanent;
}

This makes all URIs that match the exact / location redirect to http://domain.com