Mobile app version of vmapp.org
Login or Join
Karen161

: How can I test for a URLs existeance before redirecting to it? I am using Apache's mod_rewrite to redirect mobile users to my mobile site based on their http_user_agent. However not all pages

@Karen161

Posted in: #Apache #Apache2 #Mobile #ModRewrite

I am using Apache's mod_rewrite to redirect mobile users to my mobile site based on their http_user_agent. However not all pages have a mobile equivalent. Also mobile pages end in .html and "full" pages end in .shtml.

Here is some pseudo code.

Does the user have a certain HTTP_USER_AGENT?

Is there a mobile page?

If so take them there. If not, no redirection is needed.

I want to do this with apache.

10.02% popularity Vote Up Vote Down


Login to follow query

More posts by @Karen161

2 Comments

Sorted by latest first Latest Oldest Best

 

@BetL925

You CAN check for the existence of a resource identified by an HTTP URL using mod_rewrite

See example below:

RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteCond %{REQUEST_URI} ![.]html$
RewriteCond %{REQUEST_URI} ^([^.]*)
RewriteCond %1.html -U
RewriteRule ^.*$ [CO].html [R=302, L]


The import part is line 4 and the -U flag that checks if a resource exists. Note, that using this flag does impact performance on the web tier.

Other things to note. Firstly I have used a hack regex for user agent string to dtermine if the user agent is on a mobile device. This isn't always the best approach, depending on how extensible you want to make it. You might want to consider using the Apache Mobile Filter and the using a rewrite cond as follows (in place of the user agent cond):

RewriteCond %{ENV:AMF_DEVICE_IS_MOBILE} ^true


Finally, as DisgruntledGoat mentions, it is usually better to first use responsive web design and then only consider server side negotiation if you have a considerably different information architecture.

10% popularity Vote Up Vote Down


 

@Cofer257

This is not possible using htaccess alone. You would need to serve a PHP page that does the checking and redirection if the user agent is mobile. This might get very complex since if the mobile page does not exist you need to load the original .shtml file.

In this situation the best you can aim for is just redirecting users, then if the page doesn't exist, the 404 page can generate a link back to the original page (with a parameter stating not to redirect again).

However, you may be better off using other methods. Try looking into responsive web design, which allows you to serve the exact same file to different devices and have the content fit perfectly.

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme