htaccess URL rewrite with $_get function usage - php

I have been trying to do a htaccess URL rewrite (R=302) for a website which uses a $_get function to pull the content pages by use of strings. For instance, I am trying to change the following:
http://www.site.com/index.php?page=about
Into this:
http://www.site.com/about/
However, I have managed to get it set up to the point where it will redirect the header and footer data within the index.php file if I use query the second URL, but it will not grab the CSS or the $_get information for the content. Here are the htaccess entries and the $_get information:
RewriteEngine On
RewriteBase /
RewriteRule ^(.*?)/$ /index.php?page=$1 [NC,QSA,L]
RewriteRule ^(.*?)/$ $1.html [NC,L,QSA,R=302]
<?php
$folder = '';
$ext = 'html';
if (!$_GET['page'] || strpos($_GET['page'], '/') === true)
$path = 'home.' . $ext;
else $path = $_GET['page'] . '.' . $ext;
if (!file_exists($path)) {
$messages = array(
'404: Page does not exist; Please check the URL you entered.',
'404: Error 404, please check the URL of the page.'
);
print $messages[ rand(0, (count($messages) - 1)) ];
}
elseif (!#include($path)) print '300: couldn\'t get the page';
?>
Any help would be appreciated. I have been trying to modify the php code unsuccessfully thinking that is the issue.

First off, your two rewrite rules have the same condition, so only the first one will ever be met. I think you probably only want to rewrite if the requested uri doesn't exist on the server.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*?)/?$ /index.php?x=$1 [L]

Related

Rewrite URL string for username in root directory Apache

Currently I have the following .htaccess file:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME}% !-d
RewriteCond %{REQUEST_FILENAME}% !-f
RewriteRule \.(js|css)$ - [L]
RewriteRule ^/?u/(.*?)/?$ /user-profile?user_id=$1 [L]
RewriteRule ^(.+)$ index.php [QSA,L]
It rewrites all files and directories to index.php, which does further routing, ignoring static js/css files.
With this line:
RewriteRule ^/?u/(.*?)/?$ /user-profile?user_id=$1 [L]
I am redirecting all requests to something like website.com/user-profile?user_id=timm to website.com/u/timm. I'm trying to figure out how to make it redirect to simply website.com/timm, but everything I have tried so far has given me a 500 error.
Here is the solution I ended up going with, if anyone ever finds themselves in a similar situation. It might not match up to anyone else's use case, but you never know.
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME}% !-d
RewriteCond %{REQUEST_FILENAME}% !-f
RewriteRule \.(js|css)$ - [L]
RewriteRule ^/?edit-list/(.*?)/?$ /edit-list?list_id=$1 [L]
RewriteRule ^(.*)$ index.php?username-router=$1 [QSA,L]
My entire router looks like this:
// Routing
$redirect = $_SERVER['REDIRECT_URL'];
$method = $_SERVER['REQUEST_METHOD'];
// Get the path after the hostname
$path = ltrim($redirect, '/');
// Check if path matches a user
$username = $userControl->getUserByUsername(ltrim($path));
// Get controller name by converting URL of dashes
// (such as forgot-password) to uppercase class names
// (such as ForgotPassword) and assign to the proper
// controller based on URL.
$controllerName = getControllerName($redirect);
$controllerPath = $root . "/src/controllers/{$controllerName}.php";
// Load index page first
if ($controllerName === '') {
$controller = new Index($session, $userControl);
}
// If the controller exists, route to the proper controlller
elseif (file_exists($controllerPath)) { // to do: add approved filenames
$controller = new $controllerName($session, $userControl);
}
// If path matches user in the database, route to the public
// user profile.
elseif ($username) {
$controller = new UserProfile($session, $userControl);
}
// If all else fails, 404.
else {
$controller = new ExceptionNotFound($session, $userControl);
}
// Detect if method is GET or POST and route accordingly.
if ($method === 'POST') {
$controller->post();
} else {
$controller->get();
}

PHP Apache Rewrite Rules and Variables

I'm trying to get action value from variables in this url.
Real Url
index.php?action=ok&id=45&name=LG-Optimus
Friendly Url
home/ok/1/LG-P88
This above friendly url show when redirect an page like this
header('Location: /home/ok/' . $id . '/' . $name);
The page script that contains the code to get the variables
$ok = isset($_GET['ok']) ? $_GET['ok'] : "";
if($ok=='ok'){
echo "<div class='popup'>";
echo "<strong>{$card-name}</strong> added!";
echo "";
echo "</div>";
}
But i get 'Undefined index ok'.
The .htaccess file contains this code
# Turn Rewrite Engine On
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
# Rewrite for index.php
RewriteRule ^home index.php [NC,L]
# Rewrite for card-name
RewriteRule ^home/([0-9]+)/([0-9a-zA-Z_-]+)$ index.php?action=$1&id=$2&name=$3 [QSA,L]
Thanks for any help.
You are setting the GET-variable action to "ok", but your code presumes the variable is NAMED "ok".
To check it in your code you should use:
$action = isset($_GET['action']) ? $_GET['action'] : "";
if($action=='ok'){
Another thing, your regular expression lacks the "action" argument, try this:
^home/(.*)/([0-9]+)/([0-9a-zA-Z_-]+)$
You have some errors in this code. use this code
RewriteRule ^home/([a-z]+)/([0-9]+)/([0-9a-z_-]+)$ index.php?ok=$1&id=$2&name=$3 [QSA,L,NC]
Also for security reasons you must avoid from direct use of $_GET . (see)

php if variable match dir unset variable

I want to protect pages from the actual path so I'm using the server uri variable to know what the user write in the nav bar:
page.php
if ($_SERVER['REQUEST_URI'] == '/path/to/page.php') {
unset($_SERVER['REQUEST_URI']); // nothing will be displayed
} else // page content
And it's working fine, but now the problem is ?id=x or just adding ? will show the page with errors.
Is there a way to add OR == ?....
I want to prevent the direct access, because I'm using a router that includes those pages in index.php like this: site.com/page and site.com/page?...
Thank YOU!
EDIT: Add more info:
.htaccess
Options -Indexes
DirectoryIndex index.php
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
the router in index.php
// array whitelist for match
$includes = array(
'/home' => 'dir/to/home.php',
'/other' => 'dir/to/other/page.php'
);
if ($_SERVER['REQUEST_URI'] == '/')
$_SERVER['REQUEST_URI'] = '/home';
preg_match('/^([\w\/]+)/', $_SERVER['REQUEST_URI'], $matches);
$matches[1] = isset($matches[1]) ? $matches[1] : null;
if(array_key_exists($matches[1], $includes)) {
$content = include($includes[$matches[1]]);
} else $content = include('views/error.php');
return $content;
I don't know if I understand, but if you do this way:
if (preg_match('\/path\/to\/page\.php', $_SERVER['REQUEST_URI'] ))

How to get the URI of the frontpage?

I use the following code to request the URI in order to display multi-language content variables. That works fine for every page that has an URI. My problem is the frontpage: For the pure domain www.domain.com without URI it doesn't work, however it works for www.domain.com/index.php. I can't figure out the right syntax for the frontpage, please help.
if (stripos($_SERVER['REQUEST_URI'],'index') !== false ) {
// Frontpage
$lang['META_TITLE'] = 'Welcome to the frontpage';
$lang['META_DESCRIPTION'] = '';
$lang['META_KEYORDS'] = '';
$lang['PAGE_TITLE'] = '';
$lang['BREADCRUMB'] = '';
}
Create a .htaccess file in main root and paste this code .... i hope its work for you
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

Rewrite Url Parameters - Change http://myweb/?dept=dept&app=app to http://myweb/dept/app

I've currently got a web application that I need optimizing, and one of methods or something I'm trying to achieve is such:
http://myweb/dept/app
from
http://myweb/?dept=dept&app=app
I've currently this as the PHP code for it:
if(empty($_REQUEST['dept'])) {
$folder = "apps/";
} else {
$folder = str_replace("/", "", $_REQUEST['dept']) . "/"; }
if(empty($_REQUEST['n'])) {
include('user/home.php');
} else {
$app = $_REQUEST['n'];
if(file_exists($folder.$app.".php")) {
include($folder.$app.".php");
} else {
include("global/error/404.php");
}
}
How do I do this?
I'm currently half there with:
RewriteRule ^([A-Za-z]+)$ /index.php?app=$1
but that only rewrites part of it.
Thanks
The way many frameworks do this is with one of the following rules:
RewriteRule ^(.*)$ /index.php?q=$1
RewriteRule ^(.*)$ /index.php
In the 1st case you get the query string in $_GET["q"].
In the 2nd case you have to get the query string from $_REQUEST or something. (just do some var_dumps till you find what you need).
Then you explode("/") this and you're all set.
Have a look at how TYPO3, eZPublish, Drupal do this.
You should also add the following conditions to allow the site to open your static files (like images/css/js/etc). They tell apache to not do the rewrite if the URL points to a location that actually matches a file, directoy or symlink. (You must do this before the RewriteRule directive)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
This should work:
RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ index.php?dept=$1&app=$2 [QSA]
You need the QSA part in order for any GET parameters to be appended to the rewritten URL.
You might find that it can be more flexible to rewrite everything to index.php, and then handle splitting up the url there, e.g.
.htaccess:
#only rewrite paths that don't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1
PHP:
<?php
$parts = explode('/', $_SERVER['PATH_INFO']);
$dept = isset($parts[0]) ? $parts[0] : 'someDefault';
$app = isset($parts[1]) ? $parts[1] : 'anotherDefault';

Categories