htaccess rewrite rule with : in the url on windows - apache

I'm trying to do a rewrite rule that'll allow only P00:0:R It's for a pagination system for a website.
I tried it using php, and it works fine. But how do I get something like this into a rewrite rule?
$x = 'P10:10:R';
if(pageNos($x)) {
echo 'Passed';
} else {
echo 'Failed';
}
//
function pageNos($page) {
if(preg_match('/^[P]{1}[0-9]{1,10}[:]{1}[0-9]{1,10}[:]{1}[L|R]{1}$/',$page)) {
return true;
} else {
return false;
}
}
All I get with rule is
RewriteEngine On
RewriteRule ^/?([P]{1}[0-9]{1,10}[:]{1}[0-9]{1,10}[:]{1}[L|R]{1}+)/?$ /test/index.php [NC,L]
Forbidden
You don't have permission to access /P10:2:R on this server.

You're getting forbidden error because : is not allowed in URLs by Apache on Windows. On Windows the colon is forbidden as it is used as the drive letter separator.
However do note that colon (:) is allowed as a valid character under Linux and other non-windows platforms.

Related

Redirect, Hide Folder Name and enabling URL access with multiple subdirectory [duplicate]

I have a URL that looks like:
url.com/picture.php?id=51
How would I go about converting that URL to:
picture.php/Some-text-goes-here/51
I think WordPress does the same.
How do I go about making friendly URLs in PHP?
You can essentially do this 2 ways:
The .htaccess route with mod_rewrite
Add a file called .htaccess in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:
The PHP route
Put the following in your .htaccess instead: (note the leading slash)
FallbackResource /index.php
This will tell it to run your index.php for all files it cannot normally find in your site. In there you can then for example:
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
if(empty($elements[0])) { // No path elements means home
ShowHomepage();
} else switch(array_shift($elements)) // Pop off first item and switch
{
case 'Some-text-goes-here':
ShowPicture($elements); // passes rest of parameters to internal function
break;
case 'more':
...
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}
This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess will do fine though.
If you only want to change the route for picture.php then adding rewrite rule in .htaccess will serve your needs, but, if you want the URL rewriting as in Wordpress then PHP is the way. Here is simple example to begin with.
Folder structure
There are two files that are needed in the root folder, .htaccess and index.php, and it would be good to place the rest of the .php files in separate folder, like inc/.
root/
inc/
.htaccess
index.php
.htaccess
RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
This file has four directives:
RewriteEngine - enable the rewriting engine
RewriteRule - deny access to all files in inc/ folder, redirect any call to that folder to index.php
RewriteCond - allow direct access to all other files ( like images, css or scripts )
RewriteRule - redirect anything else to index.php
index.php
Because everything is now redirected to index.php, there will be determined if the url is correct, all parameters are present, and if the type of parameters are correct.
To test the url we need to have a set of rules, and the best tool for that is a regular expression. By using regular expressions we will kill two flies with one blow. Url, to pass this test must have all the required parameters that are tested on allowed characters. Here are some examples of rules.
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
Next is to prepare the request uri.
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
Now that we have the request uri, the final step is to test uri on regular expression rules.
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
}
}
Successful match will, since we use named subpatterns in regex, fill the $params array almost the same as PHP fills the $_GET array. However, when using a dynamic url, $_GET array is populated without any checks of the parameters.
/picture/some+text/51
Array
(
[0] => /picture/some text/51
[text] => some text
[1] => some text
[id] => 51
[2] => 51
)
picture.php?text=some+text&id=51
Array
(
[text] => some text
[id] => 51
)
These few lines of code and a basic knowing of regular expressions is enough to start building a solid routing system.
Complete source
define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
include( INCLUDE_DIR . $action . '.php' );
// exit to avoid the 404 message
exit();
}
}
// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );
this is an .htaccess file that forward almost all to index.php
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
# otherwise forward it to index.php
RewriteRule . index.php
then is up to you parse $_SERVER["REQUEST_URI"] and route to picture.php or whatever
PHP is not what you are looking for, check out mod_rewrite
Although already answered, and author's intent is to create a front controller type app but I am posting literal rule for problem asked. if someone having the problem for same.
RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/([\d]+)$ $1?id=$3 [L]
Above should work for url picture.php/Some-text-goes-here/51. without using a index.php as a redirect app.

Nginx rewrite part of URL with GeoIP variables

I have a URL like this:
https://example.com/home/anything/whatever
I need to rewrite this URL and replace the /home/ part with the variables from GeoIP and http-request-language:
https://example.com/ch/de/anything/whatever
I have a location match on the root that already does this and this works:
location = / {
rewrite ^ $location_uri$lang permanent;
}
Now i need this for the case above and i used:
location ~ /home/(.*) {
rewrite ^/home/(.*)$ /$location_uri$lang/$1/ permanent;
}
The original reqeust part of the URL ($1) is not added to the end of the URL:
https://example.com/ch/de//
If I remove the 2 variables $location_uri and $lang and replace them with a fix text (/ch/de) it works.
Is it possible to have these variables in the rewrite?
I managed to do it with 2 rewrites:
location ~ ^/home(.*)$ {
rewrite ^/home(.*)$ /$location_uri$lang$request_uri permanent;
}
location ~ ^/ch/de/home(.*)$ {
rewrite ^(.*)/home(.*)$ $1$2 permanent;
}
First I rewrite /home/ with the GeoIP vars and add the whole request URI including /home/.
Then I make another location-match on the target-URI and remove the /home part.

Redirect loop in CI after installing SSL Certificate

I just installed ssl certificate on my site to change the URL from http:// to https:// Everything is complete and i also added a code in my httpd.conf file to automatically add https :// to the UR So the connection is always secure.
However I am facing a problem when i try to login into the Admin Panel. It Goes in a redirect Loop and the webpage gives me a "This webpage has a redirect loop" Error.
https://mysite.com Loads fine but https:/mysite.com/admin goes into a redirect loop.
site is built up using codeigniter Framework for php.
Please Help.
I added this code to my httpd.conf file
#
# Redirect http Request to https
# The lines below are used to redirect http request to https
#
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</IfModule>
Open config file from location application/config/config.php and enable or set hooks to true like this:
$config['enable_hooks'] = TRUE;
Then create a new file named hooks.php inside the config folder (i.e. application/config/hooks.php) and add the following code in it:
$hook['post_controller_constructor'][] = array(
'function' => 'redirect_ssl',
'filename' => 'ssl.php',
'filepath' => 'hooks'
);
Now create a new directory named hooks inside the application folder (i.e. application/hooks) and then create a new file named ssl.php inside the hooks folder (i.e. application/hooks/ssl.php).
Add the following code in the ssl.php file:
function redirect_ssl() {
$CI =& get_instance();
$class = $CI->router->fetch_class();
$exclude = array('client'); // add more controller name to exclude ssl.
if(!in_array($class,$exclude)) {
// redirecting to ssl.
$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
} else {
// redirecting with no ssl.
$CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
}
}

Recursively look in subdirectories for matching filename.

if a file is not found, i would like to recursively check in subdirectories until a file with the requested name is found and deliver that.
example:
the request is:
http://domain.com/file.txt
look recursively in subdirectories until file.txt is found, then deliver:
http://domain.com/foo/bar/file.txt
the only thing i have managed so far is the trigger when a file is not found:
RewriteCond %{REQUEST_FILENAME} !-f
Take this into a loader script. First, have this rewrite in your application (vhost configuration or .htaccess file)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /loader.php?q=$1 [L,QSA]
Then have a loader.php script in the root directory of your website, that would search for a file recursively and either redirect to the proper URL or load the file, get the mime tipe, set the proper headers and respond with the content of that file. Something like this:
<?php
// Do some processing here to extract the proper file name
// from $_REQUEST['q'] into a variable called $filename
// Assume we have the $filename
$it = new RecursiveDirectoryIterator(__DIR__); // Start search where loader.php is located
foreach (new RecursiveIteratorIterator($it) as $file) {
if (pathinfo($file, PATHINFO_BASENAME) == $filename) {
$returnFile = $file;
break;
}
}
// Check if the file was found
// Do a proper redirect to the 404 page here if you need more
if (empty($returnFile)) {
header ("HTTP/1.0 404 Not Found");
die();
}
// You need to do some fancy magic here to set the proper content type
// We will return plain text for now
header("Content-Type:text/plain");
// Handle large files
set_time_limit(0);
$file = #fopen($file_path,"rb");
while(!feof($file))
{
print(#fread($file, 1024*8));
ob_flush();
flush();
}
/* EndOfScript */
And that's about it, I guess... I haven't tested this AT ALL, so there might be a lot wrong with it! Then again, you can get the main picture of how you can handle this issue!

Redirect full website address to another address - Apache

How can I redirect the following via a virtual host:
http://www.surveys.abc.com/index.php?sid=14414&newtest=Y&lang=en
to
http://www.abc.com
You don't really need to use Apache's mod_rewrite for that.
You can tweak your PHP code in index.php to look for those appropriate values in $_GET and then do the PHP redirect like this:
if (isset($_GET['sid']) && ($_GET['sid']==14414) && isset($_GET['newtest']) && ($_GET['newtest']==Y) && isset($_GET['lang']) && ($_GET['lang']=="en") ) {
header( 'Location: http://www.abc.com' );
}