I have a script that on certain events blocks someones ip via a htaccess deny from.
This is the code:
file_put_contents('.htaccess', 'deny from ' . $_SERVER['REMOTE_ADDR'] . "\n", FILE_APPEND);
Yet what i want is instead od deny from this user can i have it redirect the user to another page.
I can do this via:
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_HOST} !^123\.45\.67\.89
RewriteRule \.html$ /alternate_page.html [R=302,L]
But is it possible to do it without opening the htaccess and appending to it. Instead use the file_put_contents function
Thanks A Lot.
You don't need to use .htaccess for redirecting users to other pages, just use the location header based on what you get from $_SERVER['REMOTE_ADDR']:
header("Location: http://anothersite.com")
and don't forget this (from the PHP manual):
Remember that header() must be called
before any actual output is sent,
either by normal HTML tags, blank
lines in a file, or from PHP. It is a
very common error to read code with
include(), or require(), functions, or
another file access function, and have
spaces or empty lines that are output
before header() is called.
I would recommend storing IP addresses you do not want to allow in a database. This makes administration and if you want stats, they can be added easily as well (ie. How many times has this user tried to access the site after being denied, etd). You could even send certain IPs to different location if you wanted.
Store the IP addresses in a database table
When a user comes to the page check to see if their IP is in the table
If so increment stats counter (if desired) and redirect user to new location
Or continue loading the current page
Use php's Header function Header('Location: [url here]'); to redirect them and remember it must be before any other content is sent to the page.
What you can do is have your .htaccess file like this:
Options +FollowSymLinks
RewriteEngine on
# ADD RULES HERE
RewriteCond x x # This is a dummy condition that is always true
RewriteRule \.html$ /aternate_page.html [R=302,L]
Then you can have your replacement work like this:
<?php
file_put_contents(".htaccess",str_replace("# ADD RULES HERE","# ADD RULES HERE\nRewriteCond %{REMOTE_HOST} ^".$_SERVER['REMOTE_ADDR']."$",file_get_contents(".htaccess"));
?>
HTH
(Edit: This doesn't seem quite right... So may need a little editing. Hope the general idea helps, though.)
The proper way would be to use a gatekeeper function, which checks the IP, and forwards the request to the required page on need.
<?php
header('Location: http://www.yoursite.com/new_page.php');
?>
You should call this before any output is sent to the browser, including any HTML tags or white space. The common way is to have a 'forward' function wrapping the header command, and do access control first, before sending any content.
Related
I have a php website with a docs folder in the root, the structure of the site is thus:
sitename.com/docs/
In the docs folder are PDF's that sometimes cause browser issues because of spaces in the names, so they are not found (mainly by IE).
What I would like to do is the following:
Whenever there is a broken URL in the docs/ directory, I would like to redirect the entire query string to a php page within the docs directory, but it must keep the name of the PDF intact.
Thus, is the URL is:
website.com/docs/this is a pdf
I want it to redirect to:
website.com/docs/index.php?pdf=this is a pdf
From there, I can grab the PDF param and fix it up and send the request to the correct file.
The reason this is not done with straight .htaccess is that I cannot find a solution that is dynamic, in other words the number of words in the PDF is variable, and could be from 1 to 20 words, separated by spaces.
I had a post up here about that at this SO post which did get one reply, however, it still does not address the variable URL length problem.
I have again tried this from the examples in this tutorial but this has not helped me at all as I cannot fathom how to do this properly.
The one thing that I think is close is the following code:
RewriteEngine on
RewriteRule ^docs/(.*) /index.php?pdf=$1 [NC]
Am I close?
First you should know that, only static codes can be written in .htaccess, and we cannot process to a dynamic code,The Following solution might help for you am not testedRewriteEngine onRewriteRule ^docs/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ /index.php?pdf=$1 [L]
Have your rule like this:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
RewriteRule ^docs/((?=[^\s]*\s).+?)/?$ /docs/index.php?pdf=$1 [NC,L,B,QSA]
This will forward all PDFs with spaces to /docs/index.php while leaving non space file names intact.
Ok, so I have set the .htaccess like so:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)$ index.php
so as you can see I'm parsing everything to index except files because I need to "include" the php files and also displaying of images.
If users will type for example www.site.com/login.php that will show the login php page.
How do I prevent access to the php pages but also allow to "include" them?
Move them outside of your document root. They can be safely included from there but not accessed over the web.
If I understand the question do you want to not allow the user to go to other files if not logged in ? If so you can use php sessions to set a variable that they are logged in otherwise redirect to index
(If I understand the question)
If you wanna go that route (the outside webroot advise is the correct one!) then you could use a rule like that (see regex negative lookahead):
RewriteRule ^(?!index).+\.php$ - [F]
That's sloppy in that would allow index2.php or indexdir/xyz.php still; it just pevents anything that's not index*.php from being accessed. Make sure to also disallow .cgi or .phtml or .tpl if need be.
i want to redirect
http://testsite.com/campus.php
to
http://testsite.com/campus.php
but the file campus.php doesn't exists. It fetches the page content from database and it must be displayed.
I haven't got any idea.
First of all, your two URLs are the same.
But if you want to call a page that doesn't actually exist but is pulled from the database, you typically redirect some part of the URL to point into a $_GET variable used to access the database. All requests actually go to index.php, and index.php handles the database and displays the correct data.
# Conisde this pseudocode
# Rewrite somepage to index.php?pagename=somepage
RewriteRule /somepage.php /index.php?pagename=somepage
# The actual .htaccess rewrite looks like:
RewriteEngine On
# Assuming pagename is upper/lower letters and numbers only...
RewriteRule /([A-Za-z0-9]+)\.php /index.php?pagename=$1
Now in your PHP, you use $_GET['pagename'] (campus in your case, I think) to call the text from the database and display it.
EDIT I added the \.php to the RewriteRule. Now /campus.php rewrites to /index.php?pagename=campus
I have a URL such as http://www.domain.com/index.php?p=register. I want to redirect that to use HTTPS (SSL) with .htaccess, but only on this, and a couple of other pages (the login page, etc), but not the entire site. The URLs don't point to directories, but are used to dynamically include different files.
Can someone give me a pointer or an example of how to get a single page redirect to HTTPS please?
Thanks.
Not htaccess, but another way could be to use PHP to redirect:
<?php
$redirectlist = array('register','login','myaccount');
if (in_array($_GET['p'], $redirectlist) && strtolower($_SERVER['HTTPS']) != 'on') {
exit(header("location: https://{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}"));
}
?>
The only reason I mention this is that, in some cases, this may be easier to maintain than a separate htaccess. You would need to put this in place in your PHP content before any text was outputted (see header()).
something like this should work:
RewriteEngine on
RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{QUERY_STRING} (^|&)p=(register|login|or|other|protected|page)($|&)
RewriteRule (.*) https://www.domain.com/index.php [R=301,QSA,L]
Some explanation:
Check if server port is different from 443 (standard for secure connections), to ensure we are going to redirect only non-secured connections
The query string (everything after ?) have to match pattern: include p variable with one value from pipe separated list
Redirect everything to secure domain, sending 301 response status, appending all query string and marking is as last rule, so any rules below this will not be parsed (since this is redirect, we don't want to take any other actions)
If you have option to follow the php method, I would recommend to follow that or with any other dynamic languages. You must avoid using htaccess since links to images, js and other contact on that page will be forced to be nonSSL and modern browsers would show a non-compliance sign which might look a whitewash over your SSL cost.
Iam working on Ubuntu.(Linux)
I want to redirect from the page one.php to two.php, which are in a folder 'test'
How can i do this, using .htaccess file?
Any other setting is needed for this?
Or .htaccess redirection will not work for local system
It should work fine. Assuming the URL is http://localhost/test/one.php:
RewriteEngine On
RewriteBase /test/
RewriteRule ^one\.php$ two.php [L]
That'll do an invisible redirection—the browser won't know, and won't show it in the URL. If you want to do a different kind of redirect, you can specify R=### in the flags, where ### is the HTTP status code. For example, to perform a permanent redirect:
RewriteRule ^one\.php$ two.php [R=301,L]
the question title says "using .Htaccess", but in the last line of the question you said .htacess are not working.
so here is a solution without using .htaccess at all.
you could add a simple function in one.php file to send headers to the client (the web browser for example) to resend the request to the second address, say: two.php.
open file one.php and add this line of code in it:
<?php
header('Location: two.php');
?>
make sure you have print/echo anything (even a simple space character) before this code. because this line sends the HTTP header to the client, but if you output anything before this line, it would have gone in the body so headers will be closed.
In your test folder, you can put a .htaccess file, with the RewriteRule to do that redirection :
RewriteEngine On
RewriteRule one.php two.php
With this, the page executed on the server would be two.php ; but the URL in the browser would still be one.php
Depending on whether you want this redirection to be seen from the user, you'll to set, or not, the redirection code, and use, or not, the [R] flag.
For a permanent redirection, that would appear in the browser (i.e. the URL would really become two.php in the browser's address bar), you'd use :
RewriteEngine On
RewriteRule one.php two.php [R=301]
For more informations, you can take a look at the URL Rewriting Guide