301 redirect with regex: how to match any file at top domain level (not in a subdirectory)?

301 redirect with regex: how to match any file at top domain level (not in a subdirectory)? - If a page has internal and external outgoing links to redirecting URLs, it’s returning 3xx (301, 302, etc.) HTTP status codes standing for redirection. This issue means that the page does not exist on a permanent or temporary basis. It appears on most of the popular web browsers, usually caused by a misconfigured website. However, there are some steps you can take to ensure the issue isn’t on your side. You can find more details about redirecting URLs by reading the Google Search Central overview. In this article, we’ll go over how you can fix the 301 redirect with regex: how to match any file at top domain level (not in a subdirectory)? error on your web browser. Problem :


I need to redirect URLs of all .dmg files at domain's top level to specific folder.


By way of example:


http://example.com/file.dmg to http://example.com/downloads/file.dmg


I can't hard code the domain name because it's a temporary domain which will be switched once the new website is completed.


I don't understand why the following doesn't work:


RewriteRule ^.*.com/(.*).dmg$ /downloads/$1.dmg [R=301,L,NC] 

I get "page not found" error. A .htaccess tester website also reports failure.


What am I missing?


It's a WordPress website if it makes any difference.


Solution :

A RewriteRule only matches the file path. You can't include part of the domain name in the rewrite rule because the rule will never match it.


To match something at the start of the path, use the "starts with" regex operator: ^.


To ensure that you are not matching anything in sub-directories, make sure not to match any slashes in your pattern. [^/]+ instead of .* means "at least one character that isn't a slash" rather than "zero or more characters". The caret inside the square bracket is the negation of a character set.


Your final rewrite rule should be:


RewriteRule ^/?([^/]+.dmg)$ /downloads/$1 [R=301,L,NC]


  • ^/?: starts with an optional slash

  • (...): parenthesis around the file name (including ".dmg") which becomes $1 in the replacement

  • [^/]+: At least one character other than slashes

  • .: A literal period

  • $: "ends with", ensure there is nothing after the file name


Make sure this rewrite rule is at the top of your .htaccess file so that it takes precedence over other rewrite rules including the default wordpress rules.


We hope that this article has helped you resolve the htaccess, redirects, wordpress error in your web browsers. Enjoy browsing the internet uninterrupted!

Comments

Popular posts from this blog

How to redirect to any domain [duplicate]

"302 found" for index page bad for SEO?

Create redirect from url like www.example.us/?p=100&option=