Categories
Linux Tech

Static Page Sites: How to clean URL structure on Nginx

Static Sites are all the rage these days because they are:

  • super-fast (static pages which can also be cached in memory for further speed)
  • impossible to hack (how can you hack non-executable html pages?)
  • very low load on the server (minimal processing)

However, you will often find broken links due to minor changes in the URL structure, which a CMS like WordPress will intelligently handle. To solve this, I propose a simple structure for all static pages:

  • /a/ OR /a/index.html OR /a.html all redirects to /a which is served by /a.html
  • /a/b.html OR /a/b/ or /a/b/index.html all redirects to /a/b which is served by /a/b.html

This creates a unified view and without inconsistencies while resolving common error cases. The corresponding Nginx configuration snippet is:

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        rewrite ^/index/?$ / permanent;
        rewrite ^/$ /index.html break;
        rewrite ^(.+)/+$ $1 permanent;
        rewrite ^(.+)\.html $1 permanent;
        rewrite ^(.+)/index(\.html)?$ $1 permanent;

        root /var/www/html;
        index index.html index.htm;
        server_name _;
        location / {
                try_files $uri $uri.html $uri/ =404;
        }

Note that this is not the complete code but relevant snippet to get you started. Feel free to ask if you have any questions.

One reply on “Static Page Sites: How to clean URL structure on Nginx”

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.