I have set up my domain to point all wildcard subdomains to my webserver. What I would like to do is to perform a rewrite url based on the value that I receive on the wildcardsubdomain.
This is a specific scenario which I am not sure how to over come.
username.mydomain.com to rewrite to mydomain.com/user.php?userid=username
&
groupname.mydomain.com to rewrite to mydomain.com/group.php?groupid=groupname
I am storing on my db on a table the types as below.
john->userid
technology->groupid
steve->userid
Macleen->userid
Sports->groupid
Would this be helpful to acheive this programatically? How can I acheive this using rewriteURL?
And I would also like to keep the URL's of the page as is till the
user navigates to another page from either user.php or group.php
Try the following:
RewriteCond %{HTTP_HOST} !^www\.mydomain\.com$ [NC]
RewriteCond %{HTTP_HOST} !^mydomain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.mydomain\.com$ [NC]
RewriteRule ^$ file.php?id=%1 [L]
You could then place some sort of id check in file.php to find out if it's a username or groupname, would only work if you had unique ids for both combined though as there's no way to seperate random.mydomain.com from random.mydomain.com.
You could then use javscript to format the url:
history.pushState({path: "url"}, "", "http://random.mydomain.com/user");
index.php :
<?php
if(preg_match('/([a-z]+).mydomain.com/i', $_SERVER['SERVER_NAME'], $matches)){
$subdomain = $matches[1];
if(YourModel::isGroupName($subdomain)){
$_GET['groupid'] = $subdomain;
require './group.php';
} else {
$_GET['userid'] = $subdomain;
require './user.php';
}
}
Related
I am trying to achieve automatic subdomain creation. I have read a lot of tutorials including:
THIS
THIS
THIS
I understood the concept and I implemented it with success in the past for user profiles, but this is a different case and I am stuck.
What I want to do, is basically something like pen.io as functionality. A user creates a page with a password and then, that page name converts into a subdomain.
I thought of doing a function that runs on the index page of the main website and that one used afterwards in HTACCESS to have something like index.php?subdomain=test and that one to redirect to test.domain.tld
EDIT:
Here is the current implementation that works when clicking on a link, but it doesn't work when accessing the url directly from the browser:
Code used in view.php:
<?php
include('inc/config.php');
$url = filter_var($_GET['url'], FILTER_SANITIZE_STRING);
$conn = new mysqli($server, $username, $password, $database) or die ('Unable to execute query. '. mysqli_error($conn));
$query = "SELECT * FROM `pages` WHERE pageTitle = '$url'";
$result = $conn->query($query);
if($row = mysqli_fetch_array($result))
{
$title = $row['pageEditableTitle'];
$content = $row['pageContent'];
echo '<h5 class="mt-5"><mark>'.$title.'</mark></h5>
<p class="lead display-7">'.$content.'</p>';
} else {
echo '<br /><div class="alert alert-info" role="alert">Subdomain does not exist.</div>';
}
$conn->close();
?>
Code used in htaccess:
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.tld
RewriteRule ^(.*)$ https://domain.tld/view.php?url=%1 [L,NC,QSA]
But this redirects www.domain.tld to domain.tld/view.php?url=www and not staying as www.domain.tld in the browser url
I presuppose that you setup a wildcard dns entry (access random.domain.tld to test it!). Then you have two options:
Correct your rewrite rules
Something like [aA-zZ] should be [a-zA-Z] and the RewriteRule should be only after the RewriteCond and not in front of it and two of them. And do you really want to force a - inside the subdomain with ([a-z0-9][-a-z0-9]+)? Maybe you should check this answer. Note: The www inside of your domain is a subdomain as well. So it would rewrite to sub.php?url=www
With the corrected rewriting random.domain.tld returns the content of random.domain.tld/sub.php?url=random. But at the moment your sub.php does not return content. Instead it returns a http redirect to the URL random.domain.tld. This means your sub.php produces an infinite loop on itself. Instead sub.php should only contain something like <?php echo $_SERVER['HTTP_HOST']; ?>.
Maybe you did not understand how URL rewriting works. Then read this answer for further explanation.
Update1
You corrected your code as follows:
RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9]+)\.domain\.tld\.?(:80)?$ [NC]
RewriteRule ([a-zA-Z0-9]+) /view.php?url=$1
But it's still wrong. As I said you need to read and understand this answer. #JoachimIsaksson uses $1 and %1 in his 2nd example:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.example\.com
RewriteRule ^(.*)$ /subdomains/%1/$1 [L,NC,QSA]
%1 is the subdomain catched through RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com. And $1 is the path catched through RewriteRule ^(.*)$. You missed to use %1.
But your code can not work as you forced an unempty alphanummeric string by RewriteRule ([a-zA-Z0-9]+). But a path could contain more than that. For example a slash or question mark. And of course it could be empty as well.
And why did you add (:80)?? Do you think someone will access your domain with a specific port?
And why the last optional dot in tld\.??
At last you need to bring the flags into question. You used the NC flag. It means your rule is case-insensitive. So why do you use [a-zA-Z0-9]? As your rule is already case-insensitive it can be [a-z0-9]. And why don't you used the L and QSA flag? They are important.
Update2
Try this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.tld
RewriteRule .* view.php?url=%1 [L,NC,QSA]
Use PHP only
$_SERVER['HTTP_HOST'] contains your full domain. This answer explains how to extract the subdomain name:
$subdomain = array_shift((explode('.', $_SERVER['HTTP_HOST'])));
Now you are able to use your general index.php to switch between your general page or the users subdomain content:
$domain_parts = explode('.', $_SERVER['HTTP_HOST']);
// access without any subdomain (TLDs like "co.uk" would "need == 4")
if (count(domain_parts) == 3) {
$subdomain = "www";
}
else {
$subdomain = array_shift($domain_parts);
}
if ($subdomain == 'www') {
// general page
}
else {
// users page
}
First of all: If you have a better title for this question let me know.
Hello , I have a site which loads content using get variable.
Let me explain it to you.
My index php file:
<?php
#check if get parameter page exists
#check if file exists
require $_GET['page] . '.php'; //if it exists require its content
?>
In that way users may go to my site and write urls like these ones below:
http://localhost/loremipsum?page=home
http://localhost/loremipsum?page=help
But to get a cleaner url I edited my .htaccess file to get urls like these ones:
http://localhost/loremipsum/home
http://localhost/loremipsum/help
The .htaccess:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) /loremipsum/?pg=$1 [L]
But I got to a point where I need other parameters, For the next url I would like to have userpreferences as the page parameter and something as the fav parameter
A url like this would work:
http://localhost/loremipsum/userpreferences&fav=something
But the goal is to get a url like this:
http://localhost/loremipsum/userpreferences/something
The problem is that nothing that I have tried have worked, This is what I thought it should work but it didn't:
RewriteRule ^(.*)/userpreferences/(a-zA-Z0-9)+ /loremipsum/?pg=$1&fav=$2 [L]
UPDATE:
I know this rule should be applied only if page parameter is equal to userpreferences and I was thinking about doing
RewriteRule ^userpreferences/(a-zA-Z0-9)+ /loremipsum/?pg=userpreferences&fav=$1 [L]
But it won't work, it seems as userpreferences would not be a string and I get a server error.
You can make a rewrite rule like so:
RewriteRule ^(.*)$ index.php?parameter=$1 [NC]
and then you get :
index.php?parameter=param/value/param/value
From the Browser you get :
http://localhost/parameter/param/value/param/value
Inside PHP file you could access your parameter:
<?php
$parameter = explode( "/", $_GET['parameter'] );
for($i = 0; $i < count($parameter); $i+=2) {
echo $parameter[$i] ." has value: ". $parameter[$i+1] ."<br />";
}
?>
I have this specific problem where I have to check URL if its part is 8 chars long hash code that is saved in my database or its just normal URL where you want to navigate.
For example if i write url :
- www.example.com/A4s8Gga3
i want to process it with my script in php file
And if i write url :
-www.example.com/my-books
-www.example.com/about
i want to navigate on those pages.
I know i have to use htaccess (so much I managed myself) and so far it looks like this :
#part1
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} (\/\w+)$ [NC]
RewriteRule ^(.*)$ mobile_redirect.php [L]
#part2
RewriteCond %{REQUEST_URI} (/|\.htm|\.php|\.html|/[^.]*)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php
My mobile_redirect.php looks like this:
ob_start();
require_once('connect.php');
$request = $_SERVER['REQUEST_URI'];
$request_hotovy = str_replace('/', '', $request);
$request_hotovy = mysql_real_escape_string($request_hotovy);
$select = "SELECT HASH_ID,OFFER FROM kasko_send_form WHERE MOBILE_HASH_ID = '".$request_hotovy."'";
$query = mysql_query($select);
if(mysql_num_rows($query) > 0){
// request is mobile hash id
$result = mysql_fetch_array($query);
$hash_id = $result['HASH_ID'];
header("Location: some_link?def=".$hash_id);
} else {
// request is normal url
header("Location: ".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
}
I know that it will end up redirecting in loop. I tried to put part1 after part2 and still have the same problem. I am using joomla and it have many urls (which im not able to write down) that are not real directories or files that is why i cant just use in my php file this solution :
ob_start();
require_once('connect.php');
$request = $_SERVER['REQUEST_URI'];
$request_hotovy = str_replace('/', '', $request);
$request_hotovy = mysql_real_escape_string($request_hotovy);
$select = "SELECT HASH_ID,OFFER FROM kasko_send_form WHERE MOBILE_HASH_ID = '".$request_hotovy."'";
$query = mysql_query($select);
if(mysql_num_rows($query) > 0){
// request is mobile hash id
$result = mysql_fetch_array($query);
$hash_id = $result['HASH_ID'];
header("Location: some_link?def=".$hash_id);
} else {
// request is normal url
header("Location: page_not_found.php");
}
Because there is clearly more url processing done in joomla after it ends reading my htaccess (i dont know much about joomla either).
Can you guys give me a hint how to process the url (then maybe alter it so it wont end up in loop and then alter it again after the part1 back to normal so it can continue processing as it would normally)?
Also if you guys have any good tutorials where I could learn such things it would be really helpfull, because i understand only basics of regex and how htaccess works ...
If you use Joomla for most of your URLs exact the one that should have this eight character string there is a simple solution for this.
Just use the regular Joomla .htaccess file and add two lines before RewriteBase /
RewriteCond %{REQUEST_URI} ^/[A-Za-z0-9]{8}$
RewriteRule .* mobile_redirect.php [L]
But the Problem here is that if you have regular URLs in Joomla with 8 character than they would be redirected es well e.g. http://example.com/lastnews
So for this URL's you have to add a exception, and the hole thing would lock like this:
RewriteCond %{REQUEST_URI} !^/latesnews$ [NC]
RewriteCond %{REQUEST_URI} !^/youandme$ [NC]
RewriteCond %{REQUEST_URI} ^/[A-Za-z0-9]{8}$
RewriteRule .* mobile_redirectt.php [L]
There is no way to redirect back to Joomla with the same URL if your script do not find a record in your DB. Either your script is handling the URL or Joomla dose it. So you have to provide a 404, or find a way to include the index.php file from Joomla in your script.
I want that anybody who comes to my site
site.com?affiliate=a12b345c67
hides the affiliate querystring completely
I'm sure it's something like this, but nothing happens
RewriteRule ^/?affiliate= / [L,R=301]
To strip affiliate= query string from your URLs, place this rule in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^affiliate=[^&]+ [NC]
RewriteRule ^ %{REQUEST_URI}? [L,R=301,NE]
First of all you need to charge the URL from which users are coming to your website. Change it to:
site.com?/a12b345c67/
.htaccess cant change your URL structure on the fly.
Let me know if its ok.
Regards.
you could save the incoming $_GET parameter(if exists) to a session(or cookie, or whatever persistent storage) and reload the page.
session_start();
if(isset($_GET['affiliate']){
$_SESSION['affiliate'] = $_GET['affiliate'];
header('location: site.com');
}
you could then use the affiliate token from the session,cookie or whatever persistent storage
I want:
sub.domain.com to load index.php
sub.domain.com?s=custom to load /custom/index.php
I'm doing this right now:
In .htaccess:
RewriteRule ^(custom)/?$ index.php?subject=$1
and in index.php I have this:
if($_GET['s'] == 'custom') {
header( 'Location: http://sub.domain.com/custom/index.php' ) ;
}
... but is it possible to do the redirect via htaccess itself depending on the GET variable?
Thanks!
Yes, you could check query string with RewriteCond
RewriteCond %{QUERY_STRING} s=custom
RewriteRule ^(.*?)$ custom/index.php [L]
With this, it redirects all requests with existing "custom" get parameter to index.php, and this can be extended :)
Idea: http://statichtml.com/2010/mod-rewrite-baseon-on-query-string.html
You probably want to use "RedirectMatch"
RedirectMatch ^sub.domain.com?s=custom$ /custom/index.php
Maybe youll need to play with the regex abit