I am having a problem with clean URLs when the URL contains a key/value pair.
Sorry for the length...but, thought it might help to understand my problem.
I am following this example (https://www.youtube.com/watch?v=lRmlDeB7Ovs) His example works, mine does not. I think that I may have to enable something else with my system...as I had to in the first line of my .htaccess file (see below) to allow mod_rewrite to work with php file types.
Objective #1: This is working
Starting simple, I want my URLs to not expose the filename extension.
Before:
localhost/rewrite/handp/anyFileName.php
After:
localhost/rewrite/handp/anyFileName <-- Good, no filename extension and the file displays properly in the browser.
I use the following rule to accomplish this:
RewriteRule ^([-\w]+)$ $1.php [NC,L]
Objective #2: This is NOT working, and I have no idea why?
Case #1: Instead of the following URL:
localhost/rewrite/handp/test.php/id=4 <-- This works: echos "value = 4"
Case #2: I would like to pass this URL:
localhost/rewrite/handp/test/4 <-- This does **NOT** work: echos "Hello"
For either URL, I want to echo 4 to the browser window.
I use the following rule to accomplish this:
RewriteRule ^test/([\d]+)$ test.php?id=$1 [NC,L]
Note: The URL does display "cleanly" in case #2, but the key/value pair is not getting passed to the test.php page and therefore, echos Hello.
test.php
<?php
if ( isset($_GET['id']) )
{
echo 'Value = ' . $_GET['id'];
}
else
{
echo 'Hello';
}
This is my .htaccess file located in the folder "handp":
# I had to add the following line in .htaccess or enable it in /etc/mime.type. I chose to put this in .htaccess.
AddType application/x-httpd-php phtml pht php
RewriteEngine on
# Any filename with no extension, then get that filename and add on the php extension.
RewriteRule ^([-\w]+)$ $1.php [NC,L]
# If you see the filename "test", slash, followed by some digits, then get filename "test", add on a php extension, and pass it the key "id" and the value.
RewriteRule ^test/([\d]+)$ test.php?id=$1 [NC,L]
home.php contains the urls that can be clicked upon
<?php
for ($ii = 0; $ii < 10; $ii++)
{
// Example: localhost/rewrite/handp/test/4
echo "<a href='test/$ii'>User $ii</a><br>";
}
?>
<-- Example: localhost/rewrite/handp/nfl_north_division -->
<p>Click Me to go to the NFL North Division.</p>
nfl_north_division.php
<h1>NFL North Division</h1>
This is my system
Version of Linux
cat /etc/lsb-release
DISTRIB_ID=LinuxMint
DISTRIB_RELEASE=17.1
DISTRIB_CODENAME=rebecca
DISTRIB_DESCRIPTION="Linux Mint 17.1 Rebecca"
Note: Linux Mint 17.1, which is based on Ubuntu 14.04 LTS
Version of Apache
apache2 -version
Server version: Apache/2.4.23 (Ubuntu)
Server built: 2016-07-11T00:00:00
DOCUMENT_ROOT: /var/www/html
Version of PHP
php -v
PHP 7.0.9-1+deb.sury.org~trusty+1 (cli) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.9-1+deb.sury.org~trusty+1, Copyright (c) 1999-2016, by Zend Technologies
Do I have another configuration issue to address as I preciously had when I solved that by adding the first line in my .htaccess file.
I would appreciate it if someone could show me how to get Objective #2 to work.
Thanks,
Mike
Related
Basically, what i want is this:
For example, I have a url that looks like this :
example.com/stories/show.php?id=$id
I want that url to look like this
example.com/stories/$id/$title
And I want the title to look like this:
I love stackoverflow to
I-love-stackoverflow
Seperating each words with a dash.
Am I supposed to pass the title along with the id??
e.g example.com/stories/show.php?id=$id&title=$title
And how do I achieve all this with .htaccess ??
A good example of what I want to do is used by stackoverflow.. Check the url of this question.
You only need some simple rule like in the below example
RewriteEngine on
# rewrite stories/<id>/<title> to show.php
RewriteCond %{REQUEST_URI} stories/([0-9]+)/([a-z\-A-Z]+)
RewriteRule (.*) show.php?id=%1&title=%2 [L]
Place the above in your .htaccess file, which should be located under the stories folder. Of course you also need to make sure so that the rewrite module is enabled on your server. This could be done by running the following commands from the terminal:
sudo a2enmod rewrite
sudo apachectl restart
Now you should be able to rewrite an url like:
http://example.com/stories/666/stack-overflow
to:
http://example.com/stories/show.php?id=666&title=stack-overflow
Then you could create your links in the following manner:
<?php
// php example
$title = "I love stackoverflow";
$id = 666;
?>
link
I think you should read up on how url rewriting really works, here is a couple of links that might be useful:
URL Rewriting for Beginners
URL Rewriting Guide
I have the following rules in a htaccess file
RewriteEngine On
RewriteRule mytest.php test.php
RewriteCond %{QUERY_STRING} !done
RewriteRule (.*) $1?done [E=TEST:itworks]
The file test.php is simply
<?php
echo "TEST = " . getenv('TEST');
?>
When I enter the request uri test.php, the environment variable TEST is defined and it echoes 'Test = itworks'. However, when I enter the request uri mytest.php, it also goes to test.php, but the environment variable TEST is not defined and it echoes 'Test =' .
Is that the expected behavior? If it is a bug in my environment, never mind. Otherwise, perhaps one could use that simple case to explain to me how it works.
When you go through mytest.php, there is an additional round through mod_rewrite.
The environment variables are then prefixed with REDIRECT_. If you check for REDIRECT_TEST, you will see the desired output
<?php
echo "TEST = " . getenv('TEST') . "/" . getenv('REDIRECT_TEST');
See Available Variables for some details.
I made a little mistake (I started a new php call within an existing php call - oops) and managed to have google start crawling a whole bunch of urls that look like this:
http://www.mydomain.com/folder/parameter/%3C/?php%20echo%20writelink();%20?%3E
I've fixed the sourcing call, but my attempts to have .htaccess rewite the page calls to
http://www.mydomain.com/folder/parameter/
have been unsuccessful.
I have tried the following:
RewriteRule ^folder/(.*)/(.*)%(.*) /folder/$1/ [NE,R=301,L]
RewriteRule ^folder/(.*)/(.*)3C/?php /folder/$1/ [R=301,L]
RewriteRule ^folder/(.*)/(.*)writelink /folder/$1/ [R=301,L]
RewriteRule ^folder/(.*)/([^/.]+)writelink /folder/$1/ [R=301,L]
But all of them are returning the same 403.
I have the test rewriterule as the first rewriterule in the file, so it isnt being usurped by something else.
(For reference, the correct rewriterule when I havent mucked up the page is
RewriteRule ^folder/(.*)/$ /content/element.php?param=$1 [L]
)
I've had problems with %ages in the path before but this time I've decided to defeat it - any suggestions?
Your URL is something like this:
http://www.mydomain.com/folder/parameter/</?php echo writelink(); ?> whithout the encoding.
The 304 code does not really indicate an error, it indicates the resource for the requested URL has not changed since last accessed or cached. Clear your brower's cache and make sure it is cleared.
The error should be 403 (Forbidden) because of the initial character < (%3C).
These errors make any rewrite rule at .htaccess useless. One way to handle this kind of problem is with a script.
EXAMPLE
Add these lines to your .htaccess file at root directory:
Options +FollowSymlinks -MultiViews
ErrorDocument 403 /Error403.php
Create Error403.php at root directory with a content similar to this one:
<?php
// The following lines should be at the top of the file
/**************Only for Debugging**********************/
echo $_SERVER[ 'REDIRECT_QUERY_STRING' ] . "<br /><br />";
echo var_dump($_REQUEST) . "<br /><br />";
/*=====================================================
NOTE: A Header error might be generated while the above
code is active. Use it only to display the incoming
parameters and delete it for normal operation.
*******************************************************/
if ( isset ( $_SERVER[ 'REDIRECT_QUERY_STRING' ] ) ) {
$QueryString = $_SERVER[ 'REDIRECT_QUERY_STRING' ]; // The query looks like this: php%20echo%20writelink();%20?%3E
// Check if it is the wrong URL
if ( preg_match( '|php%20echo%20writelink()|i', $QueryString ) ) {
header("Location: http://www.mydomain.com/folder/parameter/");
}
}
// Handle other errors
?>
In this specific case we take advantage of the fact that the string contains a question mark ?, that makes it look like a query. So we try to match the query content with preg_match().
That should do it. Modify the links accordingly if necessary, this is just an example on how to do it.
I want to create a bunch of files without an extension showing at the end. The easiest way to do that was to do this:
/usa/index.php
/usa/alaska/index.php
/usa/alabama/index.php
/usa/california/index.php
What I want to do is this
/usa/alaska.php
/usa/alabama.php
/usa/california.php
and have it show up as:
/usa/alaska
/usa/alabama
/usa/california
However, I have one more level I want to add to this, the cities
/usa/alaska/adak.php
/usa/alaska/anchorage.php
/usa/california/los-angles.php
I don't want the ".php" showing up, but then each state exists as both a file and a directory. What I want is an htaccess rule that serves up the file version of the file, not the directory which is the default. I also want to strip the .php off of the end of the files so the final result looks like
/usa
/usa/alaska (alaska.php)
/usa/alaska/adak (adak.php)
I know I can get close to this by creating all the directories and using index.php for each directory, but then I will have thousands of directories each with one file in it and updating is a pain in the butt. I would much rather have one directory with 1000 files in it, than 1000 directories with 1 file in it.
Please, can someone point me in the right direction and know that I am doing this for all 50 states.
Jim
I would also suggest using a single php (e.g. index.php) file and redirecting all urls starting with usa to it, instead of separating them in different directories and files. The you'd need a couple of rewrite rules like the following
RewriteEngine On
RewriteRule ^usa/([^/.]+)$ index.php?state=$1 [L]
RewriteRule ^usa/([^/]+)/([^/.]+)$ index.php?state=$1&city=$2 [L]
So then in your index.php you'd only need to check the $_GET parameters.
Update:
If you don't feel comfortable enough to use a database and pull the needed data from there you could always use the parameters to dynamically include/require the needed files. Something like this
<?php
$source = ''; //or the 'ROOT' directory
if(isset($_GET['state'])) $source .= $_GET['state'].'/';
if(isset($_GET['city'])) $source .= $_GET['city'].'.php';
include($source); // here $source would be something like 'alaska/adak.php'
// and is assumed that the dir 'alaska' is on the same
// level as 'index.php'
?>
But to answer your original question nevertheless you could use the following .htaccess
RewriteEngine On
RewriteRule ^usa/([^/.]+)$ usa/$1.php [L]
RewriteRule ^usa/([^/]+)/([^/.]+)$ usa/$1/$2.php [L]
what about creating just one single file:
/usa/index.php
With
$_SERVER["REQUEST_URI"]
you can read the current URI.
Well, now if a user enters "http://domain.foo/usa/alaska" for example, he will get an 404 error of course.
But to call your index.php instead, you could write this line to the .htaccess:
ErrorDocument 404 /usa/index.php
Now the index.php receives everything what is written to the URI and you can match the result and include files or handle errors.
But maybe there is a better solution with .htaccess only, don't know. :)
i am trying to learn .htaccess rewrite on my localhost what i did just enable mod_rewrite and checked it with phpinfo(); everything is fine
now i create a php file : file1.php
<?php
echo "file one working successfully";
print_r($_GET);
?>
and then created a second php file: file2.php
<?php
echo "file two working successfully";
print_r($_GET);
?>
then i created an .htaccess file and write the following rewite rule :
RewriteEngine on
RewriteRule ^file1.php$ file2.php
then i typed url http://localhost/test/file1.php i believe it should redirect to file2.php but nothing happens i similarly i tried some other code but didnt work how can i get out of it. i am using apache 2 on ubuntu 10.04 i have enabled mod_rewrite and checked it in phpinfo everything is fine then why my example is not working i m frustrated help me to get out of here.
Thank in advance
i am having all my files in the same directory that is test .htaccess too
i find this an example at http://www.workingwith.me.uk/articles/scripting/mod_rewrite and followed as it suggested but nothing seems to work
Assuming that your .htaccess file is in the root directory, with the change below accessing http://localhost/test/file1.php should give return file two working successfully
RewriteEngine on
RewriteBase /
RewriteRule ^test/file1\.php$ file2.php [NC,L]
Try
RewriteEngine on
RewriteRule ^file1\.php$ file2.php
Assuming htaccess sees . as a regex command, not as an actual ., you need to backslash it?