amplify-hosting icon indicating copy to clipboard operation
amplify-hosting copied to clipboard

Using regex matches in redirects

Open timothy-bailey-redbox opened this issue 5 years ago • 15 comments

** Please describe which feature you have a question about? ** Rewrites and redirects

** Provide additional details** I have a SPA that does client side routing. However I've been working on my SEO and want to get good 301s and 404s. I am also pre-rendering my routes to static html files, which to some degree makes the routing not behave as a SPA from a server perspective.

So I want to have: 301 "/something/" -> "/something" 301 "/something/index.html" -> "/something" 200 "/something" -> "/something/index.html"

However I also need to handle some static files that are present in the root directory, like the favicon and robots.txt etc.

I also have a "static" directory with some other assets in it that I want to exclude from the rewrites and behave like normal 200/404s.

So in my config I have:

[
    {
        "source": "/static/<*>",
        "target": "/static/<*>",
        "status": "200"
    },
    {
        "source": "/",
        "target": "/index.html",
        "status": "200"
    },
    {
        "source": "/index.html",
        "target": "/",
        "status": "301"
    },
    {
        "source": "/<slug>/index.html",
        "target": "/<slug>",
        "status": "301"
    },
    {
        "source": "/<slug>/",
        "target": "/<slug>",
        "status": "301"
    },
    {
        "source": "</(^[^.]+\\.(?=(css|gif|ico|jpg|jpeg|js|png|txt|svg|woff|woff2|ttf|map|json|xml|webmanifest)$)([^.]+$))/>",
        "target": "<$1>",
        "status": "200"
    },
    {
        "source": "/<slug>",
        "target": "/<slug>/index.html",
        "status": "200"
    },
    {
        "source": "/<*>",
        "target": "/404.html",
        "status": "404-200"
    }
]

This ALMOST works, except for the regex rule which is matching the static files in the root. The regex code is correct and is matching to the files I want. However the target location is not correct (results in a 404 response). What I want it to do is much like the rule I have for the "static" directory where it gives an accurate respose for if the file exists or not (200/404). Which means the target of that rule needs to be the regex match.

I have tried using "<*>", "<$1>", and "<1>" with no joy. Can you tell me the correct way to use the match from the regex? Or if not, what would be a better way to configure this?

timothy-bailey-redbox avatar Apr 07 '20 09:04 timothy-bailey-redbox