.htaccess - set environment variable if visitor uses mobile device
We are running a magento 2 onlineshop where we also serve some CMS pages.
I need to set the environment variable MAGE_RUN_CODE to app if the user is on a mobile device.
Currently the variable is set to app if the user accesses my website via app.company.de. If he uses company.de then default is set.
SetEnv MAGE_RUN_TYPE store
SetEnvIf Host ^company.de MAGE_RUN_CODE=default
SetEnvIf Host ^app.company.de MAGE_RUN_CODE=app
But I need the website to automatically detect if the user is on a mobile device or not and then set the environment variable accordingly.
I couldn't figure out how to read the User Agent with SetEnvIf
so I tried to just rewrite the URL so that my SetEnvIf Host...
condition matches so that the MAGE_RUN_CODE is set to app, but it does nothing if I accesss my website http://company.de
from a mobile device, it just opens it without redirect.
This is my attempt (top part found here):
# Read User Agent and see if it matches one of the mobile ones
# If YES then redirect to https://app.company.de/$1
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|googlebot-mobile|iemobile|iphone|ipod|#opera mobile|palmos|webos" [NC]
RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC]
RewriteRule ^/?(.*)$ https://app.company.de/$1 [L,R=302,QSA]
# Set the Environment for the multistores
SetEnv MAGE_RUN_TYPE store
SetEnvIf Host ^company.de MAGE_RUN_CODE=default
SetEnvIf Host ^app.company.de MAGE_RUN_CODE=app
I did some research and figured out that you can also use User-Agent
.
I just needed this code:
SetEnv MAGE_RUN_TYPE store
SetEnvIf Host ^company.de MAGE_RUN_CODE=default
SetEnvIf Host ^app.company.de MAGE_RUN_CODE=app
SetEnvIf User-Agent Android|Opera MAGE_RUN_CODE=app