How to override content type with Nginx web server

To override the content type with Nginx web server, you can use the add_header directive in the server or location block of your Nginx configuration file.

For example, to set the content type to application/json for all .json files, you can add the following in your server block:

location ~* \.json$ {
add_header Content-Type application/json;
}

You can also use add_header to set the content type for specific file types.

location ~* \.csv$ {
add_header Content-Type text/csv;
}

Remember to reload or restart Nginx after making changes to the configuration file.

sudo service nginx reload

or

sudo systemctl reload nginx

It’s also possible to use the default_type directive to set a default content type for all files that do not match any other location block. This can be useful if you want to set a default content type for files that do not have a specific content type defined in your configuration file.

For example, to set the default content type to text/html, you can add the following in your server block:

server {
default_type text/html;
...
}

It is worth noting that if you set a default content type and also set a different content type for a specific file type, the specific content type will take precedence.

It’s also possible to use content_type directive to set the content type of the response in an add_header command.

location ~* \.json$ {
add_header Content-Type application/json;
}

or

location ~* \.json$ {
add_header Content-Type $content_type;
}

It’s important to note that the above examples are just a starting point and you may need to adjust them to suit your specific requirements.

Leave a Comment