patas1818
patas1818

Reputation: 93

URL Rewrite mobiles to subdirectory

I'm using:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/mobile
RewriteCond %{DOCUMENT_ROOT}/mobile%{REQUEST_URI} -d
RewriteRule ^(.*?)/?$ /mobile/$1/ [L]

RewriteCond %{HTTP_USER_AGENT} "android|iphone|ipod" [NC]   
RewriteCond %{REQUEST_URI} !^/mobile
RewriteRule ^(.*)$ /mobile/$1 [L]

The problem is that when mobiles gets redirected the images from the root won't load. I'm using this because I need to add the subdirectory (mobile) to the url example:

www.example.com/sub/file.php
www.example.com/mobile/sub/file.php

This code works but the images in the root don't show even do the path to the src shows that theres no /mobile/ added with the htaccess rules. if I add the RewriteCond %{REQUEST_FILENAME} !-f to the secund line of conds like in the secund edit the images on the root are loading but I never get redirected to the mobile subdirectory since all of the urls exist.

RewriteCond %{REQUEST_URI} !^/mobile
RewriteCond %{DOCUMENT_ROOT}/mobile%{REQUEST_URI} -d
RewriteRule ^(.*?)/?$ /mobile/$1/ [L]

RewriteCond %{HTTP_USER_AGENT} "android|iphone|ipod" [NC]
RewriteCond %{REQUEST_FILENAME} !-f   
RewriteCond %{REQUEST_URI} !^/mobile
RewriteRule ^(.*)$ /mobile/$1 [L]

Upvotes: 0

Views: 165

Answers (2)

Raymond
Raymond

Reputation: 1

Thank you Jefrey, your response is the closest to my scenario above all I have seen so far. Just to add to the initial question asked. Say there is an htaccess in the home dir and another htaccess in the mobile dir,

  1. Which of the 2 files will contain the code above?
  2. What do I put in the other file?

Upvotes: 0

Jeffrey
Jeffrey

Reputation: 1804

Because the ALL files exist in the root directory, but not all in the mobile directory, you have two options.

The most simple one is, to make an exception for files, to not rewrite them to mobile.

RewriteCond %{REQUEST_URI} !(jpg|png|jpeg|gif)

The second option is to perform two steps: First rewrite everything to /mobile. Than if the file does not exist, rewrite it back to root, but add a mark so that it's not being rewritten again to mobile!

#In case of a mobile device, rewrite everything to mobile. (windows phone = wp or wo7 / wp8)
RewriteCond %{HTTP_USER_AGENT} "android|iphone|ipod|wp" [NC]
RewriteCond %{REQUEST_URI} !mobile
RewriteCond %{QUERY_STRING} !noRewrite
RewriteRule ^(.*?)$ /mobile/$1 [L]

#In case the file exists, good, else rewrite back to non-mobile.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/mobile
RewriteRule ^mobile/(.*)$ /$1?noRewrite [L]

The above htaccess was tested, whereas image.jpg was in the root and index.php both in root as /mobile. index.php showed the image perfectly.

Upvotes: 0

Related Questions