Nginx URL Rewriting for Unified Content Delivery with Dynamic Path Parameters
During the development of a headless CMS arhcitecture, I encountered an interesting Nginx configuration challenge. The project required serving the same static template file for multiple URL patterns while preserving URL parameters for client-side processing.
The frontend application, built with React components, needed to handle article display through a single template. For instanec, when accessing URLs like:
Both should render the same template file (article.html), with the URL segment after the path serving as the article identifier for API calls.
Let me outline the directory structure:
user@server:~$ pwd
/var/www/static
user@server:~$ tree web-content
web-content
├── home.html
└── templates
├── article.html
└── post.html
1 directory, 3 files
Standard Nginx configurations would require direct file mapping, meaning URLs would need to match actual file paths like /templates/article.html. However, the requirement was to map:
- /content/any-identifier.html → /templates/article.html
- /blog/any-identifier.html → /templates/post.html
After exploring various approaches, proxy_pass proved unsuitable as Nginx attempted to concatenate paths, resulting in file-not-found errors. The solution emerged through the rewrite directive.
The rewrite directive syntax: rewrite regex replacement [flag]
This powerful directive allows internal URL manipulation without affecting the browser's address bar.
Here's the working configuration:
nginx.conf
server_name domain.com;
root /var/www/static;
location / {
index home.html;
}
location ~* ^/content/.*\.html$ {
rewrite ^/content/(.*)$ /templates/article.html break;
}
location ~* ^/blog/.*\.html$ {
rewrite ^/blog/(.*)$ /templates/post.html break;
}
The key insight is using regex capture groups to extract dynamic parts of the URL while redirecting to a static template. The break flag prevents further rewrite processing.
Sample HTML files for testing:
home.html
<html>
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body>
<h1>Welcome to Home</h1>
</body>
</html>
article.html
<html>
<head>
<meta charset="UTF-8">
<title>Article Template</title>
</head>
<body>
<h1>Article View</h1>
<div id="article-content">Dynamic content loaded here</div>
</body>
</html>
post.html
<html>
<head>
<meta charset="UTF-8">
<title>Post Template</title>
</head>
<body>
<h1>Blog Post View</h1>
<div id="post-content">Dynamic content loaded here</div>
</body>
</html>
This configuration successfully serves the same template for multiple URL patterns while maintaining the original URL in the browser address bar, allowing JavaScript to extract and use the identifier for API calls.