apache RewriteRule no effect but ErrorDocument effect - php

I enabled the.Htaccess Apache feature. For my localhost wamp it works, because ErrorDocument 404 effect,but it seems only RewriteRule doesn't effect,Is there a problem I have written??And how to write the statement that be Annotated?Thanks a lot!
These urls are not working:
RewriteCond %{HTTP_HOST} !^www.163.com [NC]
RewriteRule ^/(.*)$ http://www.163.com/ [L]
1.RewriteRule ^http://localhost/app/track/([0-9]+)$ /index.php?app=$1
2.RewriteRule ^http://localhost/app/track/123$ /index.php?app=123

For:
RewriteRule ^localhost/app/track/([0-9]+)$ /index.php?app=$1
RewriteRule ^localhost/app/track/123$ /index.php?app=123
Delete the 'localhost/' and it works well.
I think The regexp Pattern doesn't match because my DocumentRoot with '/'.
/////
To help understand,I wrote the pseudo-code by php,reference,welcome corrections :)
$realPath = str_replace('http://localhost',DocumentRoot,$url);
redirect(test($realPath));
function test($realPath) {
$pass = false;
if(preg_match($argRegExp, str_replace(DocumentRoot, '', $realPath))) {
if(strpos($argRewriteUrl,'?') ===false){
$realPath = $argRewriteUrl.'/'.basename($realPath);
$pass = $realPath;
}else{
getArgs($realPath);//split ?xx=xx&...
}
if($realPath) {
if($r = test($realPath)){
$pass = $r;
}
}
}
if($pass) {
if($r = test($realPath)){
$pass = $r;
}
}
return $pass;
}

Related

I am confused while configuring the url using htaccess and php switch

I want to write a project with regular files. The index file has a php code where all the files opened in the URL are switches. Like for example:
index.php
<?php
if(isset($_GET['page'])){
$current_page = isset($_GET['page']) ? $_GET['page'] : '';
}else{
$current_page = 'index';
}
$result = str_replace(".php","", $current_page);
switch($result){
case 'welcome':
include('sources/welcome.php');
break;
case 'index':
include('sources/index.php');
break;
case 'profile':
// Here is the problem. I want to make Facebook style user profile system
// But the switch can not see profile username because it is working just for page names not usernames
break;
}
?>
Like the code in the index.php file, I call the pages with the switch. But everything changes when the user opens the profile page. Because I want to make the profile pages of the members just like Facebook. Like http://www.mywebproject.com/username
My created htaccess is here:
.htaccess
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
RewriteRule (?:^|/)([\w-]+)/?$ profile.php?username=$1 [L,QSA]
My question is this. How can I call members' profiles with their username in switch.
How can I call members' profiles with their username in switch because there is no every username in $thePage array.
Just pass everything to the index.php
.htaccess:
# Activate rewrite engine
RewriteEngine on
RewriteBase /root/
# If the request is not for a valid directory, file or symlink
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
# Redirect all requests to index.php
RewriteRule ^(.*)$ index\.php?/$1 [QSA]
You just pass the $_REQUEST['username'] to the profile.php and then you render your page.
Something like:
index.php
// you can do this better, this is just an example:
$request_uri = $_SERVER['REQUEST_URI'];
$params_offset = strpos($request_uri, '?');
$request_path = '';
$request_params = [];
echo 'request_uri = ', $request_uri, '<br>', PHP_EOL;
if ($params_offset > -1) {
$request_path = substr($request_uri, 0, $params_offset);
$params = explode('&', substr($request_uri, $params_offset + 1));
foreach ($params as $value) {
$key_value = explode('=', $value);
$request_params[$key_value[0]] = $key_value[1];
}
} else {
$request_path = $request_uri;
}
echo 'request_path = ', $request_path, '<br>', PHP_EOL;
echo 'request_params = ', PHP_EOL; print_r($request_params);
if (preg_match('~/root/(photos|videos|albums)/([\w-]+)~', $request_uri, $match)) {
print_r($match);
unset($match);
require_once('photos_videos_albums.php');
} else if (preg_match('~/root/([\w-]+)~', $request_uri, $match)) {
$username = $match[1];
unset($match);
require_once('profile.php');
} else if ($request_path == '/root/') {
echo 'HOME';
exit();
} else {
header('HTTP/1.0 404 Not Found');
echo "<h1>404 Not Found</h1>";
echo "The page that you have requested could not be found.";
}

i change the URL type and make it SEO friendly and get 404

before I change the URL it was like
https://dastbaz.ir/quotes.php?id=1
and then I used this PHP code
if(isset($_GET['id'])) {
$stmt = $connection->prepare("XXXXXXXXXXXXXXXXX");
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) exit('No rows');
$row = fetch_array($result);
$author_name = $_GET['id']."/".$row['author_name'];
$journalName = preg_replace('/\s+/', '_', $author_name);
if (!empty($row)) {
Header("HTTP/1.1 301 Moved Permanently");
header("Location: " . $journalName . " ");
} else {
$html = "Error: cannot find short URL";
}
}
and select author_name by using id in URL and used it in URL and now it's like:
https://dastbaz.ir/1/author_name
but I have a problem with.HTACCESS and I get 404 on these pages. if there need any changes in.HTACCESS please help me to deal with that.
htaccess Code:
AddType application/x-httpd-php56 .php
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*?)$/^(\w+) /quotes.php?id=$1
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^dastbaz.ir/ [NC]
RewriteRule ^(.*)$ https://dastbaz.ir/$1 [L,R=301]

Mod-rewrite and php not working in in get method

Having problem in mod-rewrite .HTACCESS and php.
I have a page name users.php this page display selected user and my normal link is like this users.php?member=John then i changed it to clean url like this users/member/John but my problem is when you visit the page using normal url it will work fine but now i have rewrite it in my .HTACCESS it will take me to user page but not information will display it will be empty
Here is my .HTACCESS
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+users\.php\?member=([^\s&]+) [NC]
RewriteRule ^ users/member/%1? [R=301,L]
RewriteRule ^users/member/([^/]+)/?$ users.php?member=$1 [L,QSA]
HERE IS MY PHP CODE
<?php
if(isset($_GET['member'])) {
include($root . '_inc/dbconn.php');
try{
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmtData = $db_conn->prepare("SELECT * FROM users WHERE username=:getmember ");
$stmtData->bindParam(":getmember", $_GET['member']);
$stmtData->execute();
$UserData = $stmtData->fetch(PDO::FETCH_OBJ);
if ($UserData) {
$Dusername = $UserData->username;
$Dphoto = $UserData->photo;
$Demail = $UserData->email;
}
}
catch(PDOException $e)
{
echo "Error:" . $e->getMessage();
}
$db_conn = null;
}
?>
<?php echo $Dusername;?>
The problem is your RewriteCond. You have to negate the condition (note the '!' sign):
RewriteCond %{REQUEST_URI} !^[A-Z]{3,}\s/+users\.php\?member=([^\s&]+) [NC]
RewriteRule ^users/member/%1? [R=301,L]
RewriteRule ^users/member/([^/]+)/?$ users.php?member=$1 [L,QSA]
You can test your Rewrite Rules on online htaccess tester.

Clean URL on localhost

I'm trying to achieve clean URLs on my localhost (so when I write localhost/contact, it redirects me to localhost/contact.php), but it's not working. I did it according to the older tutorial I found on YouTube, but I probably didn't understand well some parts. Many thanks for every answer. Here is my code:
.htaccess // I am sure I have mod_rewrite allowed.
<IfModule mod_rewrite.so>
RewriteEngine On
RewriteBase /www/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1
</IfModule>
Script in index.php
include_once('classes/simpleUrl.php');
$url = new simpleUrl('localhost');
$test = $url->segment(1);
if (!$url->segment(1)) {
$page = 'home';
}
else {
$page = $url->segment(1);
}
switch ($page) {
case 'home' :
echo 'Home page';
break;
case 'contact':
echo 'Contacts page';
break;
default:
echo '404';
break;
}
classes/simpleUrl.php
class simpleUrl {
var $site_path;
function __toString() {
return $this->site_path;
}
private function removeSlash($string) {
if ($string[strlen($string) - 1] == '/') {
$string = rtrim($string, '/');
return $string;
}
}
function __construct($site_path) {
$this->site_path = $this->removeSlash($site_path);
}
function segment($segment) {
$url = str_replace($this->site_path, '', $_SERVER['REQUEST_URI']);
$url = explode('/', $url);
if(isset($url[$segment])) {return $url[$segment];} else {return false;}
return $url;
}
$url = new simpleUrl('localhost');
localhost is not shown in $_SERVER['REQUEST_URI'] so in this case you may simply use $url = new simpleUrl('index.php');
OR
Use this code for .htaccess :
RewriteEngine On
RewriteBase /www/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ index.php [L]
because when you do this:
RewriteRule ^(.*)$ index.php/$1
Your actual URL may become something like this:
localhost/index.php/contact
So it's better requested URL to stay same.
but in this case use:
$url = new simpleUrl('');
Oho, look at this mistery:
private function removeSlash($string) {
if ($string[strlen($string) - 1] == '/') {
$string = rtrim($string, '/');
return $string;
}
}
when passed $string does not ends with slash it returns nothing, so have to change it in such:
private function removeSlash($string) {
if ($string[strlen($string) - 1] == '/') {
$string = rtrim($string, '/');
}
return $string;
}
Now I'll explain when and why to use $site_path for simpleUrl constructor:
if you have running your script in subdirectory, for ex: if you are working under /www/test/ then you should you test as param to pass to simpleUrl constructor, otherwise leave it blank
Update 3
You should change simpleUrls segment method to this:
function segment($segment) {
$url = trim(str_replace($this->site_path, '', $_SERVER['REQUEST_URI']),'/');
$url = explode('/', $url);
if(isset($url[$segment])) {return $url[$segment];} else {return false;}
return $url;
}
and next use 0 as index instead of 1 - $url->segment(0)
I'm not sure if you wish to use more variables like: www.domain.com/folder-with-website/products/product-name or if you could live with: www.domain.com/folder-with-website/products?id=123
But try this:
index.php
<?php
$page = $_GET["page"];
if(file_exists("pages/{$page}.php")) {
include("pages/{$page}.php");
} else if(empty($page)) {
include("pages/home.php");
} else {
echo "This page does not exists";
}
?>
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1
Options -Indexes
Link setup
<ul>
<li>
Home <!-- Just a page without any variables -->
</li><li>
Products <!-- same as Home -->
</li><li>
Details about product <!-- Page with a variable / extra information -->
</li><li>
Details about product <!-- Page with more variables -->
</li>
</ul>

Mod_Rewrite PHP issue

I have actually tried the tutorial stated in here: http://net.tutsplus.com/tutorials/other/using-htaccess-files-for-pretty-urls
I have tried to use the PHP version of the Tutorial. However it doesn't seems to work. In fact it looks a little bit illogical for me.
This is the code which I'd need to place to the .htaccess file:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^.*$ ./index.php
As I have tested this actually redirects everything to the index.php file. So I have inserted this code to my index.php file:
$request = $_SERVER['REQUEST_URI'];
$params = split("/", $request);
$safe_pages = array("login");
if(in_array($params[0], $safe_pages)) {
echo 'ok'; //insert a file here
} else {
echo 'not ok'; //header to 403.php
}
This code is quite starightforward. If the URI is /login it should echo: "ok" (insert the file there).
However whenever I type: mywebsite.com/login it just always gives me the index.php, with the message: "not ok" so something should be wrong with the php code I guess.
Your are missing one more method on the .htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
This should suport url like 'page/item'
<?php
$request = $_SERVER['QUERY_STRING'];
$params = explode("/", $request);
$safe_pages = array("login");
if(in_array($params[0], $safe_pages)) {
echo 'ok'; //insert a file here
} else {
echo 'not ok'; //header to 403.php
}
?>
This dont work with url like 'page/item'
This should work:
<?php
$request = $_SERVER['REQUEST_URI'];
$params = explode("/", $request);
$safe_pages = array("login");
$last_item = count($params)-1;
if(in_array($params[$last_item], $safe_pages)) {
echo 'ok'; //insert a file here
} else {
echo 'not ok'; //header to 403.php
}
You are testing the wrong item. You should check for the string 'login' in the end of the array. And the function split is depreciated, use explode()

Categories