PHP Redirect location with htaccess - php

In one of the page I have is where administrators are allowed, however, I use if the session isn't set, the header will redirect them to index.php and that method works.
If I replace index.php with home which is for the htaccess which changes it to index.php but it gives an error in the browser
This works:
if(!isset($_SESSION['MEMBER'])){ header("Location: index.php"); }
This does not work:
if(!isset($_SESSION['MEMBER'])){ header("Location: home"); }
htaccess:
RewriteRule ^home$ index.php
The error in Firefox:
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this
address in a way that will never
complete.
This problem can sometimes be caused by disabling or refusing to accept
cookies.
What's wrong with it? How do I get this method to work?

You're redirecting index.php to home in your php file, and home to index.php in .htaccess. Firefox is telling you there is an infinite redirect loop.
Edit:
index.php and home are the same thing, so redirecting to either will result in an infinite loop. You need to do something like this:
#.htaccess
RewriteRule ^home$ index.php # public page
RewriteRule ^members$ members.php # member only page
And then in index.php
# index.php
if(isset($_SESSION['MEMBER'])){
header("Location: members");
exit;
}

Au Contraire. Here is how you carry PHP sessions id's within an .htaccess redirect...
RewriteEngine On
RewriteRule ^(.*)$ /home/ [QSA,L,E=REDIRECT_URL:$1]
Pay attention to the last bit... [QSA,L,E=REDIRECT_URL:$1]

You've created an infinite loop.
When PHP executes the following code:
if(!isset($_SESSION['MEMBER'])){ header("Location: home"); }
It redirects the browser to /home.
But in .htaccess you rewrite the URL to /index.php. Which then again makes PHP to execute the above PHP code.

Related

How can I redirect users from a webpage or another webpage to a webpage

I need something like this
<?php
if http://growtopiajaw.my.vg
else if https://growtopiajaw.my.vg
then
header('Location: https://growtopiajaw.my.vg/homepage.html', true, 301);
exit();
?>
Basiclly, if I type in the URL growtopiajaw.my.vg, it will automaticlly redirect to https://growtopiajaw.my.vg/homepage.html. But when I type in the URL https://growtopiajaw.my.vg, it will keep refreshing in an infinite loop.
I know that some people will try to access the https://growtopiajaw.my.vg page.
I don't want my site to be problematic for users. Also, you can try visiting the site https://www.growtopiajaw.my.vg. You can see that it keeps refreshing the page non-stop.
So, I am seeking help from anyone who can help me. Thank you!
EDIT:
Okay, so my question is not quite clear. What I actually meant was something like this. Redirect http://growtopiajaw.my.vg and https://growtopiajaw.my.vg (if the user went to this URL) to a specific page on https which makes the link https://growtopiajaw.my.vg/homepage.html. I currently have the code below in http://growtopiajaw.my.vg/index.html.
<?php
header('Location: https://growtopiajaw.my.vg/homepage.html', true, 301);
exit();
?>
The server will automaticlly load the index.html so it will redirect to the page https:/growtopiajaw.my.vg/homepage.html. (I cannot post more than 8 links. sorry)
So there are two possible scenarios that may apply here...
Scenario 1 - Redirect all HTTP traffic to HTTPS
You can achieve this by simply adding an .htaccess to the root of your project with the following contents...
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Notice the type of redirect here... it is 301 which translates to permanent redirect (vs. 302, which translates to temporary redirection)
Source: GoDaddy
Scenario 2 - Redirect (only) the landing page to HTTPS
A landing page is basically PAGE_NAME.EXT. This can have many forms... for example, consider the following excerpt from a hosting provider--
Our Web servers look for index files in this order:
index.html index.htm index.shtml index.php index.php5 index.php4
index.php3 index.cgi default.html default.htm home.html home.htm
Index.html Index.htm Index.shtml Index.php Index.cgi Default.html
Default.htm Home.html Home.htm placeholder.html
If the top level of
your website contains a file with any of those names, that file will
be shown when visitors don't specify a file name.
Source: TigerTech
For simplicity sake, let's say your default landing page is index.html.
In which case, simply create index.html in the root of your project and add the following--
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://growtopiajaw.my.vg/homepage.html");
exit();
?>
Now, any attempts to load //growtopiajaw.my.vg should take the user to https://growtopiajaw.my.vg/homepage.html
Notice though, this will redirect ONLY IF the user enters the growtopiajaw.my.vg URL --- if they go to growtopiajaw.my.vg/about.html then it will undoubtedly take them to a HTTP version of such a page.
Place a php file named index.php in your root directory. Write your code in it.
<?php
header('Location: https://growtopiajaw.my.vg/homepage.html');
exit;
Now all requests to http://growtopiajaw.my.vg and https://growtopiajaw.my.vg will be redirected to https://growtopiajaw.my.vg/homepage.html
I suggest you rename homepage.html to index.php and then add the following code above the doctype tag
<?php
if( !isset( $_SERVER['HTTPS'] ) ) {
header( "location: https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" );
exit();
}
?>
This is all based on not being able to setup 301 rules on the server itself. Otherwise use what #Rushikumar has suggested.

Avoiding 302 redirect when setting up multiple 404 pages

My error page is a PHP file, the entirety of which is
<?php
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$parts = explode('/', $path_parts['dirname']);
if (in_array("abcde", $parts))
{
header('Location: https://example.com/vwxyz/abcde-error-page.php');
exit();
}
else
{
header('Location: https://example.com/vwxyz/error-404-page.php');
exit();
}
?>
I want users who go to a non-existent URL in the "abcde" directory to see a particular error page, and the URL should be https://example.com/vwxyz/abcde-error-page.php and the status code should be 302. This is working just fine.
I want users who go to any other non-existent URL (in the "vwxyz" directory, or anywhere else on example.com) to see https://example.com/vwxyz/error-404-page.php, but for a 404 status code to be returned, and the URL in their browser should still be whatever they erroneously typed in. Of course, that doesn't work with header('Location ... and I can't use file_get_contents or include because the result empties the shopping cart and logs out the user (if they were logged in).
I feel that there is a simpler way to have multiple 404 pages without editing the .htaccess file (though the argument will probably be made that that is indeed the simpler way). And it is vital that the main error page behave exactly like a normal error page, but that the other (for the "abcde" directory) be a redirect, and that that special error page for the "abcde" directory NOT be in that directory (the user gets redirected out of the directory and then shown the "error"page, which should NOT return a 404 status).
If I understand the question correctly it is pretty simple via a root .htaccess file.
# enable mod_rewrite and route the request
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} ^/abcde/?.*$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /vwxyz/abcde-error-page.php [R=302,L]
# sets a custom 404 page
ErrorDocument 404 /vwxyz/error-404-page.php
First you need to switch the rewrite engine on, then perform 3 checks:
Does the URL begin with /abcde/
Is the URL not a file
Is the URL not a directory
If those things are all true then you want to route (with a 302) to /vwxyz/abcde-error-page.php
For any genuine 404 error you can just use the default ErrorDocument 404 ... syntax.
(OK this was 6 lines in .htaccess - twice as complicated as I guessed)

Redirect from mypage.domain to mypage.domain/page with .htaccess

as the title says I would like to redirect from:
mypage.domain to mypage.domain/page
I already tried this:
RewriteEngine On
RewriteBase /
Redirect 301 / http://www.mypage.domain/page
And I get an error that the page isn't redirecting properly, and also the url points to something like:
www.mypage.domain/pagepagepagepagepagepagepagepage
Can someone help me please? Thanks in advance.
You are doing it wrong. 301 status code is used for permanent redirect and here you are redirecting it to the same domain again. So when the first redirect happens, it again comes to mypage.domain and then again the .htaccess file is consulted and again a redirect happens.
Hence in a way it goes into a loop.
A proper 301 redirect should be done in the following way:
Redirect 301 / http://mynewpage.domain/
What you need here is to redirect the landing page to a specific sub folder in the root directory. Something of the following sort would work for you:
Redirect /index.html http://mypage.domain/page/
Here the index.html can be your any landing page. It can be index.php etc.

Redirect to a Rewritten URL

OK, so I'm rewriting some page URLs for a custom PHP cart.
I've got the following rules:
RewriteRule ^category/([0-9]+)/([a-z-]+)$ /store.php?cat=$1 [L]
RewriteRule ^product/([0-9]+)/([a-z-]+)$ /product.php?id=$1 [L]
These will allow me to use a url structure like example.com/product/23/product-slug.
That part is working alright. I'm wondering what options I have for the other direction; redirecting requests for the OLD url to the NEW url. So for example, when someone goes to /product.php?id=2 I want to redirect to /products/2/slug.
Any idea how to get this done?
I tried a simple redirect, but would not work:
Redirect 301 ^/store\.php\?cat=16$ http://www.example.com/category/16/category-slug
Redirect only takes a url prefix, not a regex (e.g. /store.php or /store)
You need to try RedirectMatch:
RedirectMatch 301 ^/store\.php\?cat=16$ http://www.example.com/category/16/category-slug
Also, is it supposed to start with a /? I'm not sure (your RewriteRule entries above start with no slash, for example)
I solved this a different way: with a modification to the store.php file.
I looked at output from print_r($_SERVER) after pinging both the normal and rewritten urls. I found that $_SERVER['SCRIPT_URL'] contains "/store.php" when the normal url is hit and it contains my rewritten path when the rewritten url is hit.
This means I can do a simple test and redirect appropriately:
if ($_SERVER['SCRIPT_URL'] == "/store.php") {
// run some code that will generate the url
$rewrittenURL = generateURL();
// then add:
header("HTTP/1.0 301 Moved Permanently"); // tell spiders this is permanent
header("Location: $rewrittenURL");
}

RewriteRule is breaking $_SESSION

Everything was working fine till I added my .htaccess file. What I'm trying to do is route all my users to their profile page. So www.darudude.com/user1 routes to www.darudude.com/userinfo.php?user=user1
My .htaccess file as this:
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ userinfo.php?user=$1 [L,QSA]
However ever since I added this, it breaks my sessions. On every page I have a initialize a session, and the sessions stores the referrer. This is the piece of code that handles the important part.
if(isset($_SESSION['url'])){
$this->referrer = $_SESSION['url'];
}else{
$this->referrer = "/index.php";
}
//this echo is used to debug why this thing isn't working!!
echo "<script>alert('".$this->referrer."');</script>";
/* Set current url */
$this->url = $_SESSION['url'] = $_SERVER['PHP_SELF'];
and then I'm returned to the original page using this piece of code:
header("Location: ".$session->referrer);
So for example, without the .htaccess file, if I login through one of the pages everything works and I get redirected back to the page I logged in from (i.e. if I logged in from index.php I get redirected back to index.php; if faq.php, I get redirected back to faq.php). With the .htaccess file I keep getting sent to /userinfo.php leading me to thing its something wrong with my rewriterule
This is how its supposed to work:
index.php loads. the $_SESSION['url'] is set to index.php
a login form is enacted whos action redirects to process.php
process.php the $session->referrer is set from $_SESSION['url']
After the login is confirmed the page should redirect using: header("Location: ".$session->referrer);
This is how it worked originally without any problems.
However, after the .htaccess was created it seems to redirect me to userinfo.php. I think it has something to do with my rule.
Any ideas?
I'm not sure if I understand the problem, but the rewrite rule you're using seems to turn the request to /index.php into a request to /userinfo.php?user=/index.php which may not be what you want.
It's because you're relying on $_SERVER['PHP_SELF'], which does not include the query string (the ?user= part of the URI). It worked before because your pages didn't rely on query strings to uniquely identify themselves. You can use $_SERVER['REQUEST_URI'] instead, though look out for circumstances where you don't want the query string to be preserved and now it is being.
Incidentally, the \?* in your RewriteRule regex is doing exactly the same as thing as if it weren't there.
You could try logging in with AJAX, thus never having to refresh the page at all. A simple Google search will throw up plenty of results, see below. Even if you're not using jQuery (which alot of the tutorials seem to expect you to), it's still possible with basic Javascript, in fact that's how I wrote my AJAX log-in script before converting it to use jQuery later.
http://www.google.com/search?q=php+ajax+log-in

Categories