Can I return 404 in nginx when the URL contains a file extension?



I’m new to nginx and need to modify an application’s nginx configuration file to always return a 404 if the URL contains a file extension. My nginx.conf file is as follows:

worker_processes  1;

events {
    worker_connections  1024;

http {
    server {
        listen 80;
        server_name  localhost;

        root   /usr/share/nginx/html;
        index  index.html index.htm;
        include /etc/nginx/mime.types;

        gzip on;
        gzip_min_length 1000;
        gzip_proxied expired no-cache no-store private auth;
        gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;

        location / {
            try_files $uri $uri/ /index.html;
            expires 5m;

        location /appsettings.json {
            expires 5m;

        location /version.json {
            expires 5m;

Any advice is appreciated 🙂


Replace ext with the extension you wish to ban:

location ~ \.ext$ {
  return 404;

If you want to ban all extensions (anything with a dot really):

location ~ \. {
  return 404;

Answered By – Robert Waksmunski

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More