How to use htaccess to change image paths? - php

I have a html file that has an image:
<img src="../smilies/happy.gif" />
Is it possible to redirect this path to another using .htaccess?
So the above example would become equivalent to
<img src="http://static.example.com/smilies/happy.gif" />

Well, you might get away with redirecting all calls that end with /smilies/happy.gif to that directory, so it wouldn't matter where the call came from. That does mean you should not wish to call this to some other subedirectory, but I imagine you don't.
something like this (guessing here, cann't test, so read up on the rwriting there :)
RewriteRule ^(.*)/images/$(.*) http://static.example.com/smilies/$2 [L,R=301]
basically you are rewriting everything that has '/images/' in it to that static adress, pasting whatever was after images after the new asdress (the $2 thingy) and then indicating that this is the last command to parse (to stop strange things in the htaccess) and that you want a 301 (permanently moved) code to be sent.

I think its easier to set a variable in your config
<?php
$static_url = "http://static.example.com/";
?>
<img src="<?php echo $static_url; ?>/smilies/happy.gif" alt="" />
Its better then you have the control what came from static and the rewrite engine is slow when you call it everytime its not sooo good.

RewriteRule ^(smilies/.*)$ http://static.example.com/$1 [R]

Related

PHP search & replace img src

Ok, the situation is simple (i hope!)
I am working locally (xampp) and in my .php file i've got the following img elements :
<img src="http://example.com/images/project-1/image1.jpg"/>
<img src="http://example.com/images/project-1/image2.jpg" />
<img src="http://example.com/images/project-1/image3.jpg" />
How can I make it to run a search and replace function (with php if possible) that will fulfil the following:
1) On page load to scan the whole document and find all the above images that don't appear (broken links)
2) IF from the above we find broken images , then to replace only the part that says "http://example.com" with "http://127.0.0.1/projectfile".
So what I want is to scan the whole document for broken images and if I find x of them then to replace the src from this:
src="http://www.example.com/images/project-1/image1.jpg"
with this:
src="http://127.0.0.1/project/images/project-1/image1.jpg"
I want to do this for all the images automatic, and not manually.
Currently I am struggling to do this with jQuery but I probably I am gonna need PHP because I need to navigate to the previous folders,scan dir etc etc
Thank you for you support!
Any ideas or tips?
So far what I tried and succeeded partially as I said above is to search/replace with jQuery:
$('img').attr('src',function(i,e){
return e.replace("http://example.com","http://127.0.0.1");
})
,which ignores the live website src folder and sticks directly to the local folder but I need to make it a bit more clever :)
Use jquery error event to detect missing images and replace them. Following code should do the trick
$(document).ready(function(){
$('img').on('error',function(){
// Avoid endless loop for noexistant images
if($(this).data('alreadyChecked')) return;
$(this).data('alreadyChecked',true);
//Replace src
$(this).attr('src', $(this).attr('src').replace("http://example.com","http://127.0.0.1"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="http://example.com/images/project-1/image1.jpg"/>
<img src="http://example.com/images/project-1/image2.jpg" />
<img src="http://example.com/images/project-1/image3.jpg" />
A solution with .htaccess is the best approach for this. PHP wont do it because PHP executes before the page loads. By the time these elements are on your page, it's already too late for PHP to touch them. I'm sure a hack with jQuery could work on this but it wont be reliable and it will slow down your loads and you will likely have flicker because jQuery can't touch the items until after the page loads, and at that point your broken links will already be showing until jQuery replaces them.
Try this in your .htaccess file:
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{REQUEST_URI} \.(gif|jpg|jpeg|png)$
RewriteRule ^.*/images/(.*)/(.*)$ http://127.0.0.1/project/images/$1/$2 [L,R=301]
.htaccess will replace the URLs at the request level before PHP or jQuery ever even see the content.
The best way to achieve what you want is to use javascript/jquery and replace the href value when the condition (broken link) is met.
Thank you guys!!
Although I was initially looking for a PHP way to do this, apparently JQuery worked as well!
Thanks #Nadeem Manzoor and the rest! :)

Htaccess rewrite (Cond and) Rule to rewrite these

I've been struggling with this as I'm not so good in rewriting.
I want a URLs like these:
http://www.example.com/d/page1
http://www.example.com/d/page2
http://www.example.com/d/anythinghere
to always resolve (rewrite) to this:
http://www.example.com/dir.php
or maybe event better to:
http://www.example.com/dir
which in turn should be rewritten to /dir.php
For those who would like to know why is this needed:
I need to have my AngularJS non-single-page-app work without hashbangs where I need my pagination or anything - I want to have distinctive page URLs in order for the Web spiders to crawl my content properly.
So I'm hoping that I will be able, by making such requests resolve always in my page where AngularJS is dir.php to have links: Go to page 3
I'm still not sure if this is going to work at all. Anyway, the purpose of this rewrite thing is to force the server not to go away from this page when such a link is clicked. This just struck me: but it would create at least a page reload, wouldn't it? If so, that's really bad...
RewriteRule ^/d/(.*)$ dir.php/$1
RewriteRule ^/dir/(.*)$ dir.php/$1
First rule will change everything afer /d/ to /dir.php
Second rule will forward everything after /dir/ to /dir.php
on your menu change the link
<a href="dir.php">Your Menu <a/>
to
<a href="dir">Your Menu <a/>
in the. htaccess file try this
RewriteEngine On
RewriteRule ^dir dir.php
Actually, all my previous attempts were valid - the thing is I was getting broken layout so I assumed rewrites weren't completely correct. It turned out including <base href="/"> rectified the thing by forcing the paths to be relative to the root.

Vanity URLs with resources in other folders

I want to create shorter links for my site, eg
site.come/u/1
instead of
site.com/user.php?u=1
I've had a play with mod_rewrite but quite honestly have no idea what I'm doing with it, I can create the url but when resources are being loaded on the page, they're being loaded from /u/css/core.css instead of /css/core.css
I'm loading in css/images/js with relative URLs, is there any way to make a rewrite rule exclude certain folders without having to change all of my code to absolute urls?
Thanks
You could try with:
RewriteCond %{REQUEST_URI} ^(css|js|images)/.*$ [NC]
RewriteRule ^(.*)$ $1 [L]
And place it before any other rule.
I've tested it here and it works!
Well, you are pretty much answering your own question - instead of using relative path, you will need to use absolute path for your css.
Your browser now sees the page as www.site/u/user.php, i.e. you would need to use ../css/core.css. If your site is in the root, /css/core.css might suffice but it is much safer to use the full path (i.e. echo $webpath."css/core.css" where $wehpath will most likely be something like $webpath="http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];)
You should use absolute paths and everything will be fine.
For example you can do it like that:
<?php
$baseURL = basename($_SERVER['SCRIPT_FILENAME']);
?>
<link href="<?php echo $baseURL; ?>/css/core.css" rel="stylesheet" type="text/css" />

UrlRewriting rule does not work

I have the following PHP code:
<?php
if(isset($_GET['article']))
{
echo "<b>success</b>";
}
?>
And this html:
<a href="http://localhost/PHPTest/index.php?article_27" >Click me</a>
I am trying to come up with my own url.
By doing so, I try to use mod_rewrite(). This is what is in my .htaccess:
RewriteEngine On
RewriteBase /PHPTest/
RewriteRule ^article_([0-9]+)$ index.php?article=$1
As you can see, I try to get the article get variable..
This however doesnt work.. The htaccess does not comprehend artcile_27, for example, as article=27..
Why is that?
What should happen is that the success word should be printed whenever I press the link. The problem is that it does not.
The rule you have written would match the link http://localhost/PHPTest/article_27, if you really want to have the URL http://localhost/PHPTest/index.php?article_27 matched (which is an, at least in my oppionion, unusual URL), the correct Rewrite Rule would be the following:
RewriteRule ^index\.php\?article_([0-9]+)$ index.php?article=$1
You have to look at the whole part after the last slash.
Your rule should be:
RewriteRule ^index.php?article_([0-9]+)$ index.php?article=$1
However, I'd question the use of mod_rewrite in this way.
First of all, if your url is always just index.php?article_27 then you can get directly at "article_27" using $_SERVER['QUERY_STRING'], without mod_rewrite at all.
If you're going to use mod_rewrite, why not have your URL be /PHPTest/article/27?
RewriteRule ^article/([0-9]+) index.php?article=$1
The above will also allow /PHPTest/article/27/title_of_article_here, which gives you two nice things: the ID is still there so it's easy to retrieve server-side, and the name is in the URL so it's nice to read as a human and helps search engines. If you look in your URL bar now, you'll notice stackoverflow itself uses this method.
Open this: http://localhost/PHPTest/article_27
If it works, it means that your rewriting works. In that case, all you have to do is change the HTML:
<a href="http://localhost/PHPTest/index.php?article_27" >Click me</a>
Should be:
<a href="http://localhost/PHPTest/article_27" >Click me</a>
Or rather, just:
<a href="/PHPTest/article_27" >Click me</a>
Which makes your code more portable to another hostname, port, protocol ...

Use mod_rewrite to change directories to variables... does this work?

If I have a link, for example: dashboard/xyz/fff/ and I use modrewrite to change it to dashboard/?loc=xyz&action=fff when the page loads are loc and action available as variables to use?
If so, then here's a specific example I can't seem to get to work. My rule as it sits:
RewriteRule ^getclients/([a-z\-]+)$ /dashboard/?action=getclients&module=$1
And the link that is sending them to that url:
<li>SEO Analysis</li>
I want now to be at .com/dashboard/?action=getclients&module=$1 and use those variables to load the page content that's needed.
However: Now the page redirects to what I believe is the "right page" but the CSS is all broken. I only have plain text. Feel free to suggest another way to achieve the same effect as well perhaps using jQuery and Ajax or something to load up sections of the site.
Thanks!
If you don't want to use absolute paths, you can try rewriting the requests for images, javascript, and css. Maybe something like this:
RewriteCond %{REQUEST_FILENAME} \.(js|css|png|jpe?g|gif)$ [NC]
RewriteRule ^getclients/(.+)$ /dashboard/$1 [L]
Make sure that the file locations are exact, or the server might send the data from the wrong relative directory.
For loading css, images, js files properly from a different relative path you should specify a base URL for all relative URLs on a page like this:
<base href="http://www.example.com/dashboard/" />

Categories