If I enter the following link in the browser.
http://sub.domain.com then it will open http:/domain.com/page.php?c=sub and in the browser address bar visitors will see http://sub.domain.com.
I know it can be done by rewrite url. Can anyone please tell me the htaccess codes?
Quite contrary, it cannot be done by rewriting url.
You need to set up
DNS server (to direct all subdomains to your server)
and web-server (to accept them).
Yet you don't need no query string nor rewriting, as you can always easily have your domain from HTTP_HOST variable.
I think you should do it in two steps.
step 1:
If you have direct access to your control panel, you should go in it and create a general virtual subdomain using asterisk *
After this step you can use sub.domain.com. if you don't have acees to control panel, ask admin to do it for you.
step 2:
You should edit .htaccess file with below line
# Extract the subdomain part of domain.com
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.com$ [NC]
# Check that the subdomain part is not www and ftp and mail
RewriteCond %1 !^(www|ftp|mail)$ [NC]
# Redirect all requests to a php script passing as argument the subdomain
RewriteRule ^.*$ http://www.domain.com/page.php?c=%1 [R,L]
I hope, this helps you
Related
I'm trying to manage my htaccess file in my apache server but I don't know whats wrong to handle it.
I'm finishing a web page, that will substitute the current one, with a public part and a private part (via login form, something simple and usual functuionallity), but before launching in prod our users need to login to upload some documentation related to bank accounts.
Right now I have denied all access on htaccess with IP but mine's, but the users (the ones that need to log) havent got my IP so I've made this changes:
RewriteEngine On
#Part 1: only access to login & admin
RewriteCond %{REQUEST_URI} !login
RewriteCond %{REQUEST_URI} !admin
RewriteRule .* https://www.old-domain.com [R=302,L]
#Part 2: only access with my IP
RewriteCond %{REMOTE_ADDR} !^my.office.ip.address
RewriteRule .* https://www.old-domain.com [R=302,L]
the idea is externall IPs only can enter on login page and private part (URL have "admin" on it: "/admin/profile") but In my ofice I can navigate the whole page without restrictions.
I've usea an external htaccess checker and the rules seems to be OK
https://htaccess.madewithlove.com/?share=4a22f779-f199-414e-a015-285fb47efdb0
https://www.new-domain.com/en/login is OK
https://www.new-domain.com/admin is OK
https://www.new-domain.com/en/foobar redirects to the old (current) domain
But when I configure the htaccess file on the server with only part 1, I always got redirect to the old domain (from my office IP also), and whatever the URL is.
Thanks in advance
How do I create subdomain like http://user.mywebsite.example? Do I have to access .htaccess somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?
To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?
You're looking to create a custom A record.
I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:
*.mywebsite.example IN A 127.0.0.1
127.0.0.1 would be the IP address of your webserver. The method of actually adding the record will depend on your host.
Then you need to configure your web-server to serve all subdomains.
Nginx: server_name .mywebsite.example
Apache: ServerAlias *.mywebsite.example
Regarding .htaccess, you don't really need any rewrite rules. The HTTP_HOST header is available in PHP as well, so you can get it already, like
$username = strtok($_SERVER['HTTP_HOST'], ".");
If you don't have access to DNS/web-server config, doing it like http://mywebsite.example/user would be a lot easier to set up if it's an option.
The feature you are after is called Wildcard Subdomains. It allows you not have to setup DNS for each subdomain, and instead use Apache rewrites for the redirection. You can find a nice tutorial here, but there are thousands of tutorials out there. Here is the necessary code from that tutorial:
<VirtualHost 111.22.33.55>
DocumentRoot /www/subdomain
ServerName www.domain.example
ServerAlias *.domain.example
</VirtualHost>
However as it required the use of VirtualHosts it must be set in the server's httpd.conf file, instead of a local .htaccess.
I do it a little different from Mark. I pass the entire domain and grab the subdomain in PHP.
RewriteCond {REQUEST_URI} !\.(png|gif|jpg)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}
This ignores images and maps everything else to my index.php file. So if I go to
http://fred.mywebsite.example/album/Dance/now
I get back
http://fred.mywebsite.example/index.php?uri=album/Dance/now&hostName=fred.mywebsite.example
Then in my index.php code I just explode my username off of the hostName. This gives me nice pretty SEO URLs.
We setup wildcard DNS like they explained above. So the a record is *.yourname.example
Then all of the subdomains are actually going to the same place, but PHP treats each subdomain as a different account.
We use the following code:
$url=$_SERVER["REQUEST_URI"];
$account=str_replace(".yourdomain.com","",$url);
This code just sets the $account variable the same as the subdomain. You could then retrieve their files and other information based on their account.
This probably isn't as efficient as the ways they list above, but if you don't have access to BIND and/or limited .htaccess this method should work (as long as your host will setup the wildcard for you).
We actually use this method to connect to the customers database for a multi-company e-commerce application, but it may work for you as well.
Don't fuss around with .htaccess files when you can use [Apache mass virtual hosting][1].
From the documentation:
#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs
In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.
The only drawback is that the environment variable DOCUMENT_ROOT is not correctly set to the used subdirectory, but the default document_root in de htconfig.
[1]: http://httpd.apache.org/docs/2.0/vhosts/mass.html
Simple PHP solution for subdomains and multi-domain web apps
Step 1. Provide DNS A record as "*" for domains (or domain) you gonna serve example.org
A record => *.example.org
A record => *.example.net
Step 2. Check uniquity of logins when user registering or changing login.
Also, avoid dots in those logins.
Step 3. Then check the query
<?php
// Request was http://qwerty.example.org
$q = explode('.', $_SERVER['HTTP_HOST']);
/*
We get following array
Array
(
[0] => qwerty
[1] => example
[2] => org
)
*/
// Step 4.
// If second piece of array exists, request was for
// SUBDOMAIN which is stored in zero-piece $q[0]
// otherwise it was for DOMAIN
if(isset($q[2])) {
// Find stuff in database for login $q[0] or here it is "qwerty"
// Use $q[1] to check which domain is asked if u serve multiple domains
}
?>
This solution may serve different domains
qwerty.example.org
qwerty.example.net
johnsmith.somecompany.example
paulsmith.somecompany.example
If you need same nicks on different domains served differently,
you may need to store user choise for domain when registering login.
smith.example.org // Show info about John Smith
smith.example.net // Show info about Paul Smith
In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.
Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.
You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.
This can be achieved in .htaccess provided your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named * and specifying a folder called subdomains as the document root for wildcard subdomains. Add this to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.example$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.example$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]
Finally, create a folder for your subdomain and place the subdomains files.
I just wanted to add, that if you use CloudFlare (free), you can use their API to manage your dns with ease.
You can accomplish this via two steps.
Setup wildcard subdomain
Get the subdomain entered by user
Validate the subdomain
1. Setup wildcard subdomain
This might vary depending on your hosting provider. I use Namecheap.com, and the process was as simple as follows
go to cPanel
go to sub domains
enter "*" as the value of subdomain
Now every time you enter a random string before your domain name, it will direct to the wildcard sub domain. You can modify the contents of this wildcard subdomain.
2. Get the subdomain entered by user
You can now add a php file in the wildcard directory in file manager.
<?php
$link = $_SERVER['HTTP_HOST'];
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Wildcard Subdomain</title>
</head>
<body>
<h1>The visitor went to
<?php
echo "<br>";
print("link is: ".$link);
print("<br><br>");
echo "actual file: ".$actual_link;
?>
</h1>
</body>
</html>
3. Validate the subdomain
You might want to validate the sub domain to check if there is some user linked to it. This can be done with a check to a database.
Create Dynamic Subdomains using PHP and .htaccess
#(1) Root .htaccess
This file is redirection http://www.yourwebsite.example to http://yourwebsite.example for home page use. All of the subdomain redirection to yourwebsite_folder
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.yourwebsite.example
RewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^yourwebsite\.example $
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1
#(2) Inside Folder .htaccess
This file is rewriting the subdomain URLs.
http://yourwebsite.example/index.php?siteName=9lessons
to
http://9lessons.yourwebsite.example
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteRule (.*) index.php?siteName=%1
More .htaccess tips: Htaccess File Tutorial and Tips.
#index.php
This file contains simple PHP code, using regular expressions validating the subdomain value.
<?php
$siteName='';
if($_GET['siteName'] )
{
$sitePostName=$_GET['siteName'];
$siteNameCheck = preg_match('~^[A-Za-z0-9_]{3,20}$~i', $sitePostName);
if($siteNameCheck)
{
//Do something. Eg: Connect database and validate the siteName.
}
else
{
header("Location: http://yourwebsite.example/404.php");
}
}
?>
//HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Project Title</title>
</head>
<body>
<?php if($siteNameCheck) { ?>
//Home Page
<?php } else { ?>
//Redirect to Subdomain Page.
<?php } ?>
</body>
</html>
#No Subdomain Folder
If you are using root directory(htdocs/public_html) as a project directory, use this following .htaccess file.
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.yourwebsite.example
RewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]
RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
RewriteRule (.*) index.php?siteName=%1
I want to be able to redirect folders and subfolders (all html) to another server with different folders (php)
I have a domain with DNS redirects Cname and A field pointing the domiain (that has not changed) to new website using php.
So, I want to do the following as an example.
On the old server
http://www.domain.co.uk/folder1/subfolder1/page.html
to go to
New server
http://www.domain.co.uk/folder3/
The domain used to point at the htdocs folder on the first server but now using CNAME and an A field it points to the second (new) server
Can I just redirect bulk folders to the new folders?
Hope this makes sense
Richard
You can redirect bulk folders.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://www.otherdomain.com/$1 [R=301,L]
This is a simple code that redirects ftm domain.com to otherdomain.com. But if you want to change folder1/folder2 to folder3, well.... just think you could you possibly shrink that to a simple rule? I think below 50 pages you better off wiriting 301 redirects line by line. Otherwise, no short way.
In my project I have to make a subdomain, i.e
if the user name is XXX when he register, a sub domain will be created like XXX.example.com
how to do it?
I will use php for scripting.
I found a script that seems to do exactly that, create a subdomain on your server on demand.
It probably needs a little bit of tweaking for it to work on your particular control panel, but the review are quite positive as far as I can tell.
Link
Have you considered using htaccess and url rewriting?
Found this code that may help you:
# Rewrite <subdomain>.example.com/<path> to example.com/<subdomain>/<path>
#
# Skip rewrite if no hostname or if subdomain is www
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
# Extract (required) subdomain (%1), and first path element (%3), discard port number if present (%2)
RewriteCond %{HTTP_HOST}<>%{REQUEST_URI} ^([^.]+)\.example\.com(:80)?<>/([^/]*) [NC]
# Rewrite only when subdomain not equal to first path element (prevents mod_rewrite recursion)
RewriteCond %1<>%3 !^(.*)<>\1$ [NC]
# Rewrite to /subdomain/path
RewriteRule ^(.*) /%1/$1 [L]
Source (Post #6)
This might be a little more complex than you think.
I suggest to do some reading on mod rewriting and htaccess.
You could start here:
htaccess Tutorial
Modrewrite tutorial
Subdomain Modrewrite Example
EDIT: Or just go with one of the nice examples provided my fellow SO users. ;)
As long as this is for non-SSL sites, then by far the easiest way is not to bother - just use a wildcard DNS domain and vhost, then map any domain specific behaviours in your PHP code. If you need SSL sites then its a lot more complicated - you need to have a seperate IP address/port for each certificate - and woldcard certs can be very expensive.
If you're wanting to set up some sort of hosting package then its a bit more involved - how you go about this depends on what webserver and DNS server you are using.
Assuming (again no SSL) with Apache on Unix/POSIX/Linux and bind, then, again I'd go with a wildcard DNS entry, then:
1) create a base dir for the website, optionally populate this with a default set of files
2) add a vhost definition in its own file in /etc/httpd/conf.d named as XXX.conf
3) send a kill -HUP to the HTTPD process (causes it to read the new config files without having to do a full restart).
One thing to note is that you really shouldn't allow the httpd process direct write access to its own config files - you definitely don't want to give it root privileges. A safer solution would be to create a CLI script to perform this using the username as an argument then make it setuid and invoke it from the script run by the HTTPD process.
C.
the best way is to use a joker in your DNS server :
www.example.com. IN A 1.2.3.4
*.example.com. IN A 1.2.3.4
By this way, No subdomain has to be created : all are pointing to the same IP by default.
In your PHP code, you just have get $_SERVER["HOST"] and get the fist part :
$hostParts=explode('.',$_SERVER["HTTP_HOST"]);
$user=$hostParts[0]
First, you need to make sure you have a wildcard domain setup in DNS, and make sure your webserver (apache?) directs all queries for that wildcard domain to your php file.
Then in php you can look at $_SERVER["HTTP_HOST"] to see which subdomain is used for that particular request.
Since you will make sub-domains when an user registers.
Try this as .htaccess file:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^.htaccess$ - [f]
RewriteCond %{HTTP_HOST}!^www.domain.com
RewriteCond %{HTTP_HOST} ^([^.]+).domain.com
RewriteRule ^$(.*) /$1/%1 [L]
make a function of a controller which will take the value of sub-domain and display what necessary.
like::
public function show ($domain)
{
**.**..*..**.** Your code goes here
}
when a user will try this xxx.domain.com/controller/show this will be domain.com/controller/show/xxx . if you want to xxx.domain.com to be domain.com/controller/show/xxx just edit the htaccess file as you want.
I have two different domains that both point to my homepage in the same server.
I want to log every single access made to my homepage and log which domain the user used to access my homepage, how can I do this?
I tried mod_rewrite in Apache and logging to a MySQL database with PHP but all I could do was infinite loops.
Any ideas?
EDIT:
By your answers, I see you didn't get what I want...
As far as I know Google Analytics does not allow me to differentiate the domain being used if they both point to the same site and it also does not allow me to see that some files like images were accessed directly instead of through my webpages.
I can't also just use $_SERVER['HTTP_HOST'] cause like I just said, I want to log EVERYTHING, like images and all other files, every single request, even if it doesn't exist.
As for Webalizer, I never saw it differentiate between domains, it always assumes the default domain configure in the account and use that as root, it doesn't even display it. I'll have to check it again, but I'm not sure it will do what I want...
INFINITE LOOP:
The approach I tried involved rewriting the urls in Apche with a simple Rewrite rule pointing to a PHP script, the PHP script would log the entry into a MySQL database and the send the user back to the file with the header() function. Something like this:
.htaccess:
RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.net [NC]
RewriteRule ^(.*)$ http://www.domain1.net/logscript?a=$1 [NC,L]
RewriteCond %{HTTP_HOST} ^(www\.)?domain2\.net [NC]
RewriteRule ^(.*)$ http://www.domain2.net/logscript?a=$1 [NC,L]
PHP Script:
$url = $_GET['a'];
$domain = $_SERVER['HTTP_HOST'];
// Code to log the entry into the MySQL database
header("Location: http://$domain/$url");
exit();
So, I access some file, point that file to the PHP script and the script will log and redirect to that file... However, when PHP redirects to that file, the htaccess rules will pick it up and redirect again too the PHP script, creating an infinite loop.
The best thing do would be to parse the server logs. Those will show the domain and request. Even most shared hosting accounts provide access to the logs.
If you're going to go the rewrite route, you could use RewriteCond to check the HTTP_REFERER value to see if the referer was a local link or not.
RewriteCond %{HTTP_HOST} ^(www\.)?domain1\.net [NC]
RewriteCond %{HTTP_REFERER} !^(.*)domain1(.*)$ [NC]
RewriteRule ^(.*)$ http://www.domain1.net/logscript?a=$1 [NC,L]
RewriteCond %{HTTP_HOST} ^(.*)domain2\.net [NC]
RewriteCond %{HTTP_REFERER} !^(.*)domain2(.*)$ [NC]
RewriteRule ^(.*)$ http://www.domain2.net/logscript?a=$1 [NC,L]
You may also want to post in the mod_rewrite forum. They have a whole section about handling domains.
If Google Analytics is not your thing,
$_SERVER['HTTP_HOST']
holds the domain that is used, you can log that (along with time, browser, filepath etc). No need for mod_rewrite I think. Check print_r($_SERVER) to see other things that might be interesting to log.
Make sure to still escape (mysql_real_escape_string()) all the log values, it's trivially easy to inject SQL via the browser's user-agent string for example.
So, I access some file, point that file to the PHP script and the script will log and redirect to that file... However, when PHP redirects to that file, the htaccess rules will pick it up and redirect again too the PHP script, creating an infinite loop.
Can you check for HTTP headers in the RewriteCond? If so, try setting an extra header alongside the redirect in PHP (by convention custom HTTP headers start with 'X-' so it could be header('X-stayhere: 1');), and if the X-stayhere header is present, the RewriteCond fails and it doesn't forward the browser to the PHP script.
If, however, you can cron a script to download the server logs and run them through some freeware logfile analyzer, I'd go with that instead. Having two redirects for every request is a fair bit of overhead.. (and if I was more awake I might be able to come up with different solutions)
Does Google Analytics not provide this option? Or could you not parse your server log files?
Why not use the access log facility build in apache?
Apache have a "piped log" function that allow you redirect the access log to any program.
CustomLog "|/path/to/your/logger" common