move index.php to another directory - php

I am using this GitHub page: https://github.com/Athlon1600/php-proxy-app and as it's supposed to, when I go to development.stech.software it loads up index.php.
When I choose a link, it makes it a query string like this development.stech.software/index.php?q=y6ml06abkWPdp6pnn6PVl6TLlMSkpmdvzdzUj6WZbqbWoQ (where the random characters is the query).
How do I adjust the index.php file, so that when I go to a URL, it loads it on /index.php/query/y6ml06abkWPdp6pnn6PVl6TLlMSkpmdvzdzUj6WZbqbWoQ or something similar.
I tried this, but it wouldn't work (it reported 500), I found it from URL rewriting with PHP
$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 'index':
ShowPicture($elements); // passes rest of parameters to internal function
break;
case 'more':
...
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}
I also added this to .htaccess FallbackResource htdocs/index.php

To redirect /index.php?q=foobar to /index.php/query/foobar you can use the following Rule in your htaccess file:
FallbackResource htdocs/index.php
RewriteEngine on
RewriteCond %{QUERY_STRING} ^q=(.+)$
RewriteRule ^index.php$ /index.php/query/%1? [L,R]

Related

URL redirect to GET variables

In a PHP website I want to set a redirect if there are variables in the URL inside a specific folder (.com/promo/).
When a user visits:
www.example.com/promo/Marco-Aurelio
Redirect to:
www.example.com/promo/?user=Marco-Aurelio
What PHP code or htaccess rules would you use?
function RedirectToFolder(){
//lets get the uri
$uri = $_SERVER["REQUEST_URI"];
//remove slashes from beginning and ending
$uri = trim($uri,"/");
//lets check if the uri pattern matches the uri or not
//if it doesnt match dont continue
if(!preg_match("/promo\/(.+)/i,$uri)){
return false;
}
//lets now get the last part of the uri
$explodeUri = explode("/",$uri);
$folderName = end($explodeUri);
//lets get the new url
$redirectUrl = "http://www.example.com/promo/?user=$folderName";
Header('Location:'.$redirectUrl);
exit();
}//end function
So just call the function after the php opening tag
RedirectToFolder();
Create .htaccess in the apache DirectoryRoot containing the following:
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/promo/(?![?])(.+)
RewriteRule ^ /promo/?user=%1 [L]
So that the url
http://www.example.com/promo/Marco-Aurelio
Will be redirected to
http://www.example.com/promo/?user=Marco-Aurelio

Rewriting the URL with htaccess (apache)

I have an website where in the homepage are displayed multiple articles. Every article has a link and when I click on it I pass the Id, the date and the title as parameters through the URL to "article.php" page. When I'm on the article page I recognize which article is by the Id and then I display the content.
But my problem is: when I open the "article.php" page my URL looks like this
http://127.0.0.1/Andrea/mySite/article.php?id=21&date=02%20march%202017%title=Basket%20NBA:%20Bulls-Warriors.%20Analysis
I have created the .htaccess file and I'm able to redirect people to other pages so the rewrite is enabled, what I'm searching is to change the URL from the above to something like this
http://127.0.0.1/Andrea/mySite/2017/03/02/basket-nba-bulls-warriors
So I want to remove the "Analysis" part after the point and "article.php" from the URL, the date to switch like if it was folders and the title to be written with scores between the words.
I have tried
RewriteEngine on
RewriteRule ^id/([A-Za-z0-9-]+)/?$ article.php?id=$1 [NC]
To remove "article.php" and add id between slashes but it doesn't seem to work.
Thanks in advice to everyone who will help me.
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:
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.

Header location infinite redirect Loop

I have this huge issue that I have no idea how to fix. I have a script that redirects to a url.
So far I have:
//do some mysql
$geo_included = true; //trying to fix infinite redirect loop.
if($geo_included === true){
header('Location: '.$url["url"]); //this is causing the issue with redirect loop
}
$url["url"] for example is: www.google.com
But when I go to that PHP file it will redirect to:
www.sitename.com/www.google.com
and say there is an infinite redirect loop. Note: the above header location script is not in a while/for/foreach loop.
Here is my .htaccess for the / directory
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?group=$1 [L]
Any ideas?
You need to include the fully qualified domain name with scheme, otherwise it's interpreted as being in the current domain:
header('Location: google.com'); // Redirects to http://cursite.com/www.google.com
header('Location: http://google.com'); // Redirects as expected
If you are unsure if your URL includes a scheme, check the results from parse_url.
$url_scheme = parse_url($url, PHP_URL_SCHEME);
// www.google.com -> NULL
// http://google.com -> string(4) "http"
// ftp://site.com -> string(3) "ftp"
The quick proof-of-concept solution here is to prepend http:// to the URL like this:
$geo_included = true;
if ($geo_included) {
header('Location: http://' . $url["url"]);
}
I say “proof of concept” because what you should do is ensure the $url["url"] always has a protocol attached to it. Either before it gets into the database, or in this code snippet by doing a check on the $url["url"] value to see of it has http:// or https:// and if it doesn’t, prepend it. And here is a quickly thrown together example of what I mean which should work:
$geo_included = true;
if ($geo_included) {
$protocol = (!preg_match("~^(?:ht)tps?://~i", $url["url"])) ? 'http://' : null;
header('Location: ' $protocol . $url["url"]);
}
The line with $protocol = … does the check I explained before. The default is to add http:// if it’s not there.
Also, note I removed === true since the if ($geo_included) { is basically the same thing.

Rewrite URL in .htaccess just cause 404 error

I'm trying to learn how to rewrite URL in the .htaccess file. I have read some tutorials, but despite that I write as in the example code, nothing happens for me! I'm wondering what I'm doing wrong here? I get a 404-code when I'm trying the code below.
RewriteEngine On
RewriteRule /byggnader/1/ /?p=byggnad&id=1
This is just a test and I wonder if /byggnader/ must be an existing file or just a name in the URL. I'm using a page controler design. So URL /?p=byggnad&id=1 will open the PSelectedBuilding.php file inside the index.php file.
I preciate some feedback to be able to continue.
EDIT: Since it's not working despite the help below, I also add the code from the index.php file that handle the requests. Perhaps that could give a clue why!?
<?php
session_start();
// Allow only access to pagecontrollers through frontcontroller
$indexIsVisited = TRUE;
require_once('config.php');
// pagecontrol
$page = isset($_GET['p']) ? $_GET['p'] : 'start';
switch($page) {
case 'start': require_once('PIndex.php'); break;
case 'karta': require_once('PMap.php'); break;
case 'byggnader': require_once('PBuildings.php'); break;
case 'tips': require_once('PTips.php'); break;
case 'visa-byggnad': require_once('PHandleSessions.php'); break;
case 'byggnad': require_once('PSelectedBuilding.php'); break;
case 'visa': require_once('PSelectedBuilding.php'); break;
case 'visa2': require_once('PHandleSessions.php'); break;
default: require_once('PIndex.php'); break;
}
require_once("CreatePage.php"); // Call file that creates the page
?>
EDIT 2:
This works fine, but not when I'm using requests for some of the pages:
RewriteEngine On
RewriteRule bilder-byggnader-kopenhamn /?p=byggnader
RewriteRule karta-byggnader-kopenhamn /?p=karta
RewriteRule start /?p=start
RewriteRule tips /?p=tips
Remove leading slash from your rule. .htaccess is per directory directive and Apache strips the current directory path (thus leading slash) from RewriteRule URI pattern.
RewriteEngine On
RewriteRule ^byggnader/1/?$ /?p=byggnad&id=1 [L]
Try this one:
RewriteEngine On
RewriteCond %{QUERY_STRING} p=(\w+)&id=(\d+)
RewriteRule ^index.php /%1/%2? [R=301, L]
The RewriteCond mathches the Query String (as per your wish) extracting two variables which you can reuse to build your redirection target in the rewrite rule directive. The final question mark tells Apache not to reappend existing QS. R=301 says that the redirection is permanent, L that this is the last rule to be processed.
You may have to play with the index.php part since you never put the REQUEST_URI part in your question.

Using SERVER['REQUEST_URI'] and GET in controlling the website flow

I have a small website. It's .htaccess file is like this:
RewriteEngine On
RewriteBase /site/
RewriteRule ^(.+)$ index.php [QSA,L]
So it redirects all the URLs to 'index.php'. I can get the requested URL and act accordingly :
$uri = $_SERVER['REQUEST_URI'];
switch($uri)
{
case 'index':
LoadIndex();
break;
case 'about':
LoadAbout();
break;
case 'Posts':
LoadPosts();
break;
default:
LoadNotFound();
}
Say I want to use $_GET[] in Index page. That changes the URL, so it fails to load the page.
How can I do that? How can I route my site without affecting $_GET[] variables in URLs?
$_SERVER[REQUEST_URI] will be /index.php and not index. $_SERVER[REQUEST_URI] also includes the QUERY_STRING. So, it might be /index.php?var1=abc&var2=def.
If you need only the URI path, try PHP_SELF or SCRIPT_NAME. But keep in mind, that these will be /index.php too, including / and .php.
$uri = $_SERVER['PHP_SELF'];
switch($uri)
{
case '/index.php':
LoadIndex();
break;
...
}
You don't need QSA in your RewriteRule. From RewriteRule Directive
Modifying the Query String
By default, the query string is passed through unchanged.
This means, the $_GET variable is available in your PHP script as before.

Categories