how to redirect "www.somedomain.com/folder1/demo.jpg" request to some other page using mod_rewrite? - apache

code block:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} mysite.000webhostapp.com$ [NC]
RewriteCond %{HTTP_HOST} !folder1
RewriteRule ^(.jpg)$ http://mysite.00xxxtapp.com/folder1/$1 [R=301,L]

I think you want your filename in the new url as well? (not just ".jpg")
RewriteRule ([^/]+\.jpg)$ http://mysite.00xxxtapp.com/folder1/$1 [R=301,L]
or
RewriteRule ([^/]+\.jpg)$ /folder1/$1 [L]
if you want to keep seeing the old url
EDIT
So you need more than 1 rewriterule.
I suggest the steps
all "fake" urls redirect to some php script
all images in /folder1/ must be redirected or be made inaccessable (suggestion: put them outside the document root|)
RewriteEngine On
# all images in somefolder will be parsed through a php script
RewriteRule somefolder/([^/]+\.jpg)$ /imageshower.php [L]
# redirect to a no access image
RewriteRule folder/*\.jpg /no-access.jpg [R]
The php script will be able to do some checking like 'is the user logged in?' or does he have the rights
<?php
$filename = basename($_SERVER['REQUEST_URI']); // this still points to the jpg
if(is_file('folder/'. $filename) && is_allowed($user, $filename)) {
header('Content-Type: images/jpg'); // or other like .gif or .pdf etc
readfile('folder/'. $filename);
}
?>

Related

htaccess rewrite root url to subfolder with accessing other folder?

I have following folder structure in apache server.
Public_html
-->admin
--->admin_login.php
-->website
--->index.php
since the index.php inside the website folder,
i have given following code in .htaccess
RewriteCond %{REQUEST_URI} !^/website/
RewriteRule ^(.*)$ /website/$1 [L,NC]
so that the when the user enter root url , it will appear "www.myurl.com" instead of "www.myurl.com/website/"
but the issue is, i could not be able to access admin_login.php.
is there anyway to modify .htaccess, to come website/index.php in main url and able to access admin_login.php(both)?
Thanks in Advance
You need to add an exception to existing rule like this:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/(website|admin)/ [NC]
RewriteRule .* website/$0 [L]
Negative condition %{REQUEST_URI} !^/(website|admin)/ will match every URI except URIs that start with /website/ or /admin/. This will allow you to directly open www.myurl.com/admin/admin_login.php.
With your shown samples and attempts please try following .htaccess rules file. Please make sure to clear your browser cache before testing your URLs.
RewriteEngine ON
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^index\.php/?$ website/index.php [QSA,NC,L]

Redirect all .php requests to .html using .htaccess

The following code works to hide .php and replace it with .html
RewriteEngine ON
RewriteCond %{REQUEST_URI} ^/([^/]*)/([^.]*)\.html/?$ [NC]
RewriteRule ^(.*)$ %1/%2/index.php [L]
I would like to redirect all .php requests to .html.
All .php files are inside a sub directory in "https://www.sitename.com/user/".
For example
https://www.sitename.com/user/login/index.php
https://www.sitename.com/user/name/index.php
https://www.sitename.com/user/register/index.php
https://www.sitename.com/user/logout/index.php
https://www.sitename.com/user/dashboard/index.php
https://www.sitename.com/user/contact/index.php
It should redirect to
https://www.sitename.com/user/login.html
https://www.sitename.com/user/name.html
https://www.sitename.com/user/register.html
https://www.sitename.com/user/logout.html
https://www.sitename.com/user/dashboard.html
https://www.sitename.com/user/contact.html
Adding separate line of .htaccess code for each folder will be difficult, can someone help with simple code to automatically detect and redirect .php to .html ?
Explanation:
If some try to access "sitename.com/user/login/index.php", it should load "sitename.com/user/login.html".
sitename.com/user/login.html should be the only URL that is visible to users. Even if someone try to access "sitename.com/user/login/index.php", it should redirect/rewrite to "sitename.com/user/login.html".
Enter sitename.com/user/login.html in browser = sitename.com/user/login.html
Enter sitename.com/user/login/index.php in browser = sitename.com/user/login.html
With your shown samples, could you please try following. Please make sure you clear your browser cache before validating your URLs. As per OP's comment edited rules, as per .php and .html formats. I believe you should avoid giving both kind of urls to users and ask them to hit only .html urls in case anyone hits .php url you could forbid it(in case they are directly hitting it, another reason could be because if they are hitting .php directly then you want it to change URL on browser to .html which is actually being served by a .php file itself in backend), if they hit .html then that could be served by respective index.php of passed uri IMHO. NOTE: This is IMHO only and should not be used if someone has more requirements on this one.
RewriteEngine ON
RewriteCond %{REQUEST_URI} ^/user/([\w-]+)\.html/?$ [NC]
RewriteRule ^(.*)$ user/%1/index.php [L]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_URI} index\.php/?$ [NC]
RewriteRule ^ - [F]
You can use the following rules to convert your php URLs into html :
RewriteEngine on
#Redirect and rewrite php URLs to html
#redirect /user/foobar/index.php to /user/foobar.html
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^user/([^/]+)/index\.php$ /user/$1.html [L,R]
#rewrite /user/foobar.html to /user/foobar/index.php
RewriteRule ^user/([^.]+)\.html$ /user/$1/index.php [L]
The rule #1) triggers when /user/foobar/index.php is requested and redirects it to /user/foobar.html . Since the .html file doesn't exist the second rule maps the .html request back to original .php page but your URL remains the same in browser address bar.

.htaccess url rewriting is working but not the redirection

I'm working on a local server on an html/php application and I'm trying to use the Apache url rewrite module without success
The application was stored in ./Compta/index.php. I have to an .htaccess file in ./Compta/.htaccess
I would like to only use a rewritten url like :http://localhost/Compta/Test/
instead of : http://localhost/Compta/index.php?page=test
and redirect users if they try to go to the old url
The .htaccess file contains :
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^([[:alnum:]]*)/$ /Compta/index.php?page=$1 [L]
RewriteRule ^([[:alnum:]]*)$ /Compta/index.php?page=$1 [L]
RewriteCond %{REQUEST_URI} ^/index\.php$
RewriteCond %{QUERY_STRING} ^page=([[:alnum:]]*)$
RewriteRule ^(.*)$ http://localhost/Compta/%1/ [L,R=301]
When I go to http://localhost/Compta/Test/ the following line is working and my code includes in a div the content of test.php :
RewriteRule ^([[:alnum:]]*)/$ /Compta/index.php?page=$1 [L]
When I go to http://localhost/Compta/Test the following line is working but in firefox the url is rewritten to http://localhost/Compta/index.php?page=Test and this is not happening with http://localhost/Compta/Test2; the url isn't rewritten.
RewriteRule ^([[:alnum:]]*)$ /Compta/index.php?page=$1 [L]
To fix this and to redirect the old url I added these lines :
RewriteCond %{REQUEST_URI} ^/index\.php$
RewriteCond %{QUERY_STRING} ^page=([[:alnum:]]*)$
RewriteRule ^(.*)$ http://localhost/Compta/%1/ [L,R=301]
But this is not working and when I go to http://localhost/Compta/index.php?page=Test the url isn't rewritten to http://localhost/Compta/Test/
Thank you in advance
I didn't find a solution with .htaccess but i found one with php so i added the following lines in top of my php files :
if(preg_match("/\/Compta\/index\.php\?page=([[:alnum:]]*)/",#$_SERVER['REQUEST_URI'],$page)&&!empty($page[1]))
{
$new_url = "/Compta/";
switch (strtolower($page[1])) {
case "test":
$new_url = $new_url."Test/";
break;
case "test2":
$new_url = $new_url."Test2/";
break;
default:break;
}
header("Status: 301 Moved Permanently", false, 301);
header("Location: ".$new_url);
exit;
}
I test if the url begin with "/Compta/index.php?page=" AND if there is a parameter for "page"
Then I initialise the variable which contain the new url
Switch the content of my parameter I modify the new url
and then I make the redirection to my new url :)

Redirection by querying database value like stackoverflow.com URLs

So I use the following htaccess code to redirect the URLs to clean looking URLs but, now what I need to happen is to have the original URLs to redirect to the new clean URLS.
Example
Original URL:
example.com/search/store_info.php?store=113&dentist=Dr.%20John%20Doe
Clean URL:
example.com/search/113/dr-john-doe
What I need is the "ORIGINAL URL" to redirect to the "CLEAN URL". Reason why I need this to happen is that both URLs are showing up in Google searches.
I only want the clean URL to show up and anytime the original URL is used it should automatically redirect to the clean URL. It currently doesn't do that.
Here is my htaccess file.
ErrorDocument 404 default
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteBase /search/
RewriteCond %{QUERY_STRING} .
RewriteCond %{THE_REQUEST} /store_info\.php\?store=([a-z0-9]+)&dentist=([^\s&]+) [NC]
RewriteRule ^ %1/%2/? [L,NE,R=301]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_URI} \.(?:jpe?g|gif|bmp|png|ico|tiff|css|js)$ [NC]
RewriteRule ^ - [L]
RewriteRule ^([a-z0-9]+)/([^\s.]*)[.\s]+(.*)$ $1/$2-$3 [NC,DPI,E=DONE:1]
RewriteCond %{ENV:DONE} =1
RewriteRule ^([0-9a-z]+)/([^\s.]+)$ $1/$2 [R=301,NE,L]
RewriteRule ^([a-z0-9]+)/([a-z0-9-]+)/?$ store_info.php?store=$1&dentist=$2 [QSA,L,NC]
</IfModule>
I've read about RedirectMatch however I don't know where to implement it into my htaccess file.
Inside your store_info.php have code like this:
<?php
$store = $_GET['store'];
if (empty($store)) {
header("HTTP/1.1 404 Not Found");
exit;
}
$dentist = $_GET['dentist']);
// pull dentist from DB by store id. Create this function in PHP and
// query your database
$dentistFromDB = preg_replace('/[\h.]+/', '-', $row['businessName']);
// DB returns an empty or no value
if (empty($dentistFromDB)) {
header("HTTP/1.1 404 Not Found");
exit;
}
// DB returned value doesn't match the value in URL
if ($dentistFromDB != $dentist) {
// redirect with 301 to correct /<store>/<dentist> page
header ('HTTP/1.1 301 Moved Permanently');
header('Location: /' . $store . '/' . $dentistFromDB);
exit;
}
// rest of the PHP code should come now
?>
You do not need to clutter your htaccess file anymore with arbitrary rules/directives. The current set of rules, with the %{THE_REQUEST} matching, and later with the %{ENV=DONE} conditionals are more than enough.
Just wait a few days for google to crawl your pages again, and the older unclean urls will disappear. You could also search around in Google Webmaster Tools to see if this can be triggered manually.
PS: You can remove the RewriteCond %{QUERY_STRING} . line from your first rule.

301 redirect dynamic cgi generated urls using .htaccess

I'm having trouble making sense of this .htaccess file I've inherited at my new job. I'm a graphic designer / marketer learning web development. Our site has a bunch of duplication errors and I want to rename our links and have them 301 redirected.
This is the first part of the .htaccess file:
RewriteEngine Off
RewriteCond %{HTTP_HOST} !^blog.asseenontvhot10.com$ [NC]
RewriteCond %{REQUEST_URI} !/sitemap\.xml
AddType text/html .shtml, .html, .htm
AddHandler server-parsed .shtml, .html, .htm
AddHandler application/x-httpd-php5 .html .htm .shtml
#Options FollowSymLinks Includes -Indexes
From what I understand the first part links our blog to the main site, and I'm not sure what the next line does.
The addtype line and the ones that follow enable .htaccess to read/write those filetypes?
Here is the part that I believe is relevant and what I need to change:
RewriteEngine on
rewritecond %{http_host} ^[^.]+\.[^.]+$ [nc]
rewriterule ^(.*)$ http://www.%{http_host}/$1 [r=301,nc]
RewriteRule default.html /home.html
RewriteRule contact\.html /cgi-bin/commerce.cgi?display=contact
RewriteRule about\.html /cgi-bin/commerce.cgi?display=about
RewriteRule register\.html /cgi-bin/commerce.cgi?register=action
RewriteRule products\.html /cgi-bin/commerce.cgi?listcategories
RewriteRule parent_category/(.*)/(.*)/ /cgi-bin/commerce.cgi?listcategories=action&parent=$1
RewriteRule category/(.*)/(.*)/(.*)\.html /cgi-bin/commerce.cgi?search=action&category=$1&page=$3
RewriteRule category/(.*)/(.*)/ /cgi-bin/commerce.cgi?search=action&category=$1
RewriteRule category/(.*).html /cgi-bin/commerce.cgi?search=action&page=$1
RewriteRule product/(.*)/(.*)/ /cgi-bin/commerce.cgi?preadd=action&key=$1
RewriteRule basket\.html /cgi-bin/commerce.cgi?display=basket
RewriteRule log-in\.html /cgi-bin/commerce.cgi?login
RewriteRule home\.html /cgi-bin/commerce.cgi?display=home
RewriteRule search\.html /cgi-bin/commerce.cgi?display=search
RewriteRule all-items\.html /cgi-bin/commerce.cgi?search
RewriteRule update_user\.html /cgi-bin/commerce.cgi?displayuser=action
RewriteRule order_history\.html /cgi-bin/commerce.cgi?orderhistory
RewriteRule logout\.html /cgi-bin/commerce.cgi?logout
RewriteRule specials\.html /cgi-bin/commerce.cgi?search=action&keywords=nav_specials
I know the first part forces www. and does a 301 redirect, even though I haven't seen this way of accomplishing it on any guide I've read. The first thing I really need to change is making the home page 301 redirect from:
http://www.asseenontvhot10.com/cgi-bin/commerce.cgi?display=home
to
http://www.asseenontvhot10.com/
So far as I can tell the RewriteRule makes this an option but dosn't force it. Will adding [r=301] to the end of the rewriterule work?
I've also read that there is code you need to add for .cgi to work as .php does but I'm totally lost there.
Update:
I tried adding this line to the bottom -
Redirect 301 /cgi-bin/commerce.cgi?display=home /
and I got a 500 error.
2nd Update:
I added this code:
RewriteRule about\.html /cgi-bin/commerce.cgi?display=about
RewriteCond %{QUERY_STRING} ^display=about$
RewriteRule ^cgi-bin/commerce\.cgi$ /about [R=301]
And it 404'd. When I replaced the .htaccess file with the back up and the about page still 404's... Now I'm really at a loss and don't know how to revert the site. I don't even know where the redirect would be stored outside of the htaccess file once it's reverted.
3rd Update: (making progress)
I added this code:
RewriteRule about\.html /cgi-bin/commerce.cgi?display=about
RewriteCond %{QUERY_STRING} ^display=about$
RewriteRule ^cgi-bin/commerce\.cgi$ /about\.html? [R=301]
and I got a redirect loop. It was finally redirecting to about.html which I thought the first rule renamed /cgi-bin/commerce.cgi?display=about to, but it redirected to it over and over again.
The Redirect directive in Apache requires that the redirect destination be a fully qualified URL with a scheme and a URL. So this would work:
Redirect 301 /cgi-bin/commerce.cgi http://www.yourdomain.com/
However, I don't believe that Redirect can check the query string, so in order to only apply this redirect if the query string is "display=home" you will probably have to use mod_rewrite like this:
RewriteCond %{QUERY_STRING} ^display=home$
RewriteRule ^cgi-bin/commerce\.cgi$ / [R=301]
The RewriteCond checks that the query string exactly equals "display=home" and the RewriteRule will only trigger if this condition is met. And in the RewriteRule the [R=301] flag instructs mod_rewrite to redirect the visitor's web browser to the target path, / in this case.
By the way, looking at the existing conditions in your .htaccess file, I can't see how your users are seeing the /cgi-bin/commerce.cgi path in their web browser. All of those RewriteRule directives are for silent rewrites. This means that the user will continue to see the "friendly" URL in their web browser, but in the background Apache will actually find the file located at the /cgi-bin/commerce.cgi path and return the content or result of that file to the user. So your users should already be seeing the friendly version of the URL. If what you are trying to do instead is silently rewrite a request for "/" (site root) so that Apache silently rewrites the path and actually fetches the content in the real file /cgi-bin/commerce.cgi?display=home then you probably want this instead:
RewriteRule ^$ /cgi-bin/commerce.cgi?display=home
This will only match a request for the root directory (with no filename specified) and will silently fetch and return the content which results from calling the commerce.cgi file with a "display=home" parameter.