Nginx · December 18, 2023

Nginx Command: add_header

Nginx Command: add_header

Nginx is a popular web server that is known for its high performance, scalability, and flexibility. It is widely used to serve static content, reverse proxy, and load balance web applications. One of the powerful features of Nginx is the ability to add custom headers to HTTP responses using the add_header command.

What is the add_header command?

The add_header command in Nginx allows you to add custom headers to the HTTP response. These headers can provide additional information to the client or modify the behavior of the client or intermediate proxies.

The syntax of the add_header command is as follows:

add_header header_name header_value [always];

The header_name is the name of the header you want to add, and the header_value is the value of the header. The optional always parameter ensures that the header is added to all responses, including error responses.

Examples of using add_header

Let's look at some examples of how the add_header command can be used in Nginx configuration:

1. Adding a custom header

add_header X-Custom-Header "Hello, World!";

This example adds a custom header named X-Custom-Header with the value Hello, World! to all HTTP responses.

add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";

These examples add security-related headers to the HTTP responses. The X-Content-Type-Options header prevents the browser from MIME-sniffing the response. The X-Frame-Options header restricts the loading of the page in a frame or iframe from a different origin. The X-XSS-Protection header enables the browser's built-in Cross-Site Scripting (XSS) protection.

add_header Cache-Control "public, max-age=3600";

This example adds the Cache-Control header to enable caching of the response by intermediate proxies and the client's browser. The max-age directive specifies the maximum time in seconds that the response can be cached.

Conclusion

The add_header command in Nginx is a powerful tool for adding custom headers to HTTP responses. It allows you to provide additional information to clients, modify client behavior, and enhance security and caching capabilities. By leveraging the flexibility of Nginx, you can customize your web server to meet your specific requirements.

For more information about VPS hosting and how it can benefit your website, visit Server.HK.