How to Set Content Type in NGINX


set content type in nginx

If your website serves different types of files, it’s essential to set their content type header so they render properly. Otherwise, users may not be able to view them properly. For example, a raw text file with utf8 characters may not be displayed properly. So let us take a look at how to set content type in NGINX.

 

How to Set Content Type in NGINX

Here are the steps to set content type in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

 


$ sudo vim /etc/nginx/nginx.conf

 

2. Set Content Type Header

Although NGINX has a default content type header for each file type, you can easily override it by adding the following lines in server or location block, or even in /etc/nginx/mime.types file. Here are some examples


server / {
default_type application/html;
...
}

The above code will set the default content type for all requests

If you want to set content type for only specific URLs, then add it in location block.


location /product.xml {
default_type application/xml;
...
}

The above code will set content type for a specific URL which happens to be an XML file.
You can even set content type header in mime.types file. Open it in a text editor


$ sudo vim /etc/nginx/mime.types

Add the following lines to set content type for xml files

types {
    application/xml        dae;
}

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

That’t it! Now NGINX will automatically set the content type header for all your file types, as per your requirements.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!