Search code examples
apache.htaccessmod-rewrite

.htaccess: Redirect all URLs of website to specific page if using Opera browser


I would like to redirect users if Opera UA is detected.

The following settings work fine partially:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} OPR [NC]
RewriteRule ^$ https://example.com/sub1/ [L,R=301]

When accessing the URL https://example.com/ the user is redirected to https://example.com/sub1/ correctly, but when accessing any other URL, such as https://example.com/example-1, https://example.com/example-2, etc., the user is not redirected as expected.

I also tried the following two amended strings:

RewriteRule ^(.*)$ https://example.com/sub1/ [L,R=301]

and

RewriteRule ^(.*) https://example.com/sub1/ [L,R=301]

With both amended strings the user is redirected from any URLs to https://example.com/sub1/ properly. However, the html page is not rendered, and the following error message is displayed: "The page isn’t redirecting properly"

Does anybody know a valid RegEx I can use?


Solution

  • The problem with your last rewrite rules is that the browser is stuck in an infinite redirection loop. An infinite redirection loop happens when you visit a URL pointing to another URL, which points back to the first one. To prevent this, you must exclude the folder to which you are redirecting. Here are some possibilities for you. Also remember to change R=302 to R=301 after testing.

    RewriteCond %{REQUEST_URI} !^/sub/
    RewriteRule (.*) /sub/ [R=302,L]
    

    Which also would do the job:

    RewriteRule !sub /sub/ [R=302,L]
    

    Another solution I discovered a while ago comes from Mr. White, where the REDIRECT_STATUS environment variable is used. See here and here for Mr. White original answers and more details about this method.

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule (.*) /sub/$1 [R=302,L]