Nginx SPA URL Rewrite – How to Rewrite URLs Within a Single Page App in Nginx

nginxredirectrewrite

I've been having issues with this nginx configuration, and after scouring this site, I'm wondering if it's even possible.

I have a very simple single page app with the following routing:

server {
        listen 80 default_server;

        root /var/www/html;

        location / {
                try_files $uri $uri/ /index.html;
        }
}

The SPA (a Gatsby site, if that matters) served by this config contains routes like domain.com/about and domain.com/about/some-page that serve specific content. However, there is an older version of the website that was not a SPA and it has pages like domain.com/about.html and domain.com/about.html#some-page, and these serve equivalent content, respectively.

I'd really like to be able to redirect domain.com/about.html > domain.com/about and domain.com/about.html#some-page > domain.com/about/some-page so that old links to the site that are out in the world already still go to the correct route of the SPA, but all of my attempts to create rewrites either just return a 404 or direct back to the root.

Is it possible to both rewrite the URL (so domain.com/about.html > domain.com/about) and also redirect that URL to /index.html so it works as a SPA?

Best Answer

I was able to solve this issue by keeping the nginx configuration the same, and doing the URL rewrites on the client-side within Gatsby using Reach Router.