Nginx directives are configuration commands used in the Nginx configuration files to control the behavior of the web server. Here are some common Nginx directives along with their purposes:
Common Nginx Directives:
-
server:- Defines a virtual server block. Each server block can handle requests for a specific domain or IP address.
server { listen 80; server_name example.com; } -
location:- Specifies how to process requests for specific URIs. It can be nested within a
serverblock.
location /images/ { root /var/www/html; } - Specifies how to process requests for specific URIs. It can be nested within a
-
listen:- Defines the IP address and port that the server block will listen on.
listen 80; # Listen on port 80 -
server_name:- Specifies the domain names that the server block responds to.
server_name example.com www.example.com; -
root:- Sets the root directory for requests. This is where Nginx will look for files to serve.
root /var/www/html; -
index:- Specifies the default file to serve when a directory is requested (e.g.,
index.html).
index index.html index.htm; - Specifies the default file to serve when a directory is requested (e.g.,
-
error_page:- Defines custom error pages for specific HTTP status codes.
error_page 404 /404.html; -
proxy_pass:- Used in location blocks to forward requests to another server (reverse proxy).
location /api/ { proxy_pass http://backend-server; } -
rewrite:- Used to modify request URIs based on specified rules.
rewrite ^/old-path/(.*)$ /new-path/$1 permanent; -
log_format:- Defines the format of the logs that Nginx will write to the access log.
log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
Example Configuration:
Here’s a simple example of an Nginx configuration using some of the directives mentioned:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
error_page 404 /404.html;
}
Further Learning:
To explore more about Nginx directives and their usage, consider checking the official Nginx documentation, which provides comprehensive details on configuration options and best practices.
If you have any more questions or need further clarification, feel free to ask!
