Search code examples
apache.htaccesshttp-redirect

Redirect on condition in htaccess file


I'm trying to make some redirects on the one condition, using If block in Apache, in the .htaccess of my project. I have this:

<If "%{HTTP_HOST} == 'shoppingmall-local.ventajon.com:8433'">
  # inicio
  RedirectMatch 301 ^/tiendas-online$ https://shoppingmall-local.ventajon.com/tiendas-online

  # carrito de compras
  Redirect 301 /tiendas-online/cart https://shoppingmall-local.ventajon.com/tiendas-online/cart

# cuenta
  Redirect 301 /tiendas-online/cuenta https://shoppingmall-local.ventajon.com/tiendas-online/cuenta
</If>

But it doesn't work. When I click in the link, it doesn't redirect. I hope you can help me. Thanks in advance.


Solution

  • You've not stated the URL you are requesting (when you "click in the link") or (importantly) what other directives you have in the config file (and the corresponding placement of these directives).

    In isolation there's nothing actually wrong with the rule block you've posted (so it's likely there is a conflict with other directives), however, these rules can be simplified using mod_rewrite (which you are most certainly using already to root these requests).

    Try the following instead at the top of the root .htaccess file:

    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} ^(shoppingmall-local\.ventajon\.com):8433$
    RewriteRule ^tiendas-online(/cart|/cuenta)?$ https://%1%{REQUEST_URI} [R=301,L]
    

    This essentially does the same as your existing rule block. (Except that it won't redirect /tiendas-online/cart/<something> and /tiendas-online/cuenta/<something> as the Redirect directives would.) This rule must go near the top of the .htaccess file before any existing mod_rewrite directives.

    I'm assuming your source URLs do not contain a trailing slash.

    (You do not need to repeat the RewriteEngine directive if is already occurs later in the config file.)

    I mentioned this in comments (and this was seemingly confirmed), however, 8433 does look-like a typo. It would be more common to be using 8443 as an alternative port for HTTPS, not 8433 as you have written here?

    You should test first with a 302 (temporary) redirect to avoid potential caching issues and you should ensure the browser (and any intermediary) cache is cleared before testing.

    If you only have one hostname (ie. shoppingmall-local\.ventajon\.com) then the rule can be simplified further since you can just check for the port number instead. For example:

    RewriteCond %{SERVER_PORT} =8433
    RewriteRule ^tiendas-online(/cart|/cuenta)?$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]