I've been looking at htaccess and how to use rewrite rules in order to make a sort of "fake subdomain" for users.
so far i have:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([a-z0-9-]+)/? http://$1.domain.com [R=301,NC,L]
RewriteCond %{HTTP_HOST} ^([a-z]+)\.domain\.com$
RewriteRule ^$ index.php?user=%1
this will take any /somthing and make it a subdomain and then pass the subdomain value in as a param to pick up.
i want to be able to now use actual parameters, and pass them through normaly with the extra "user" param from the "subdomain"
e.g.
fred.domain.com/index.php?page=1&sort=up
would give me in $_GET
['user'] = 'fred'
['page']= 1
['sort'] = up
but for the life of me I cant figure out how to do this! as when i add any other params, I loose the user bit
Any help? =)
Also any helpful tutorials on htaccess would be nice! as all ones ive found haven't really explained what each bit does and why =\
Thanks in advance
.htaccess file has nothing to do here. It can't help you.
To direct a user to your server, you have to alter DNS record, not web-server config.
I am assuming that:
You own a domain, domain.com say, that is being hosted by some shared hosting service (SHS) provider.
You either have access to a control panel to set up subdomains, or your SHS provider has already set up a * A record mapping to its shared service.
Some SHS providers simply map *.domain.com to a fixed subdirectory, say /webroot/domain.com/public_html; others do this top level-redirection for their users and provide a control panel which allow account-holders to associate subdomains with specific subdirectories.
So you need to work out which applies in your case:
by looking at your SHS providers FAQs,
by trying http://sss.domain.com/ to see if it routes to your DOCROOT
by using a phpinfo() script to see what Rewrite environment variable it uses to point to your DOCROOT. (For technical reasons in Apache, see Dynamic mass virtual hosts with mod_rewrite, %{DOCUMENT_ROOT} cannot be properly initialised for each user, so providers typically use a RewriteMap to initialise a stand-in; mine uses %{ENV:DOCUMENT_ROOT_REAL})
So let's assume that you want to set up a blog at say http://blog.domain.com/, you may need to:
Issue permanent redirects [R=301] from legacy references to http://domain.com/blog/* to http://blog.domain.com/*
Issue internal redirects from http://blog.domain.com/* to DOCROOT/blogdir/*
Add the necessary conditional interlocks to prevent infinite redirection loops, where this second internal redirect is then treated as a legacy reference.
I could give you a set of rewrite rules to do this, but given that I've answered a dozen flavours of this same Q this months, you can find lots of templates by searching or by looking at my blog (Webfusion, .htaccess) where I've written a number of articles giving more explanation.
If you want a single application to catch some wildcard subset of domain, as long as you can encode this in a regexp then you can do something like:
RewriteCond %{HTTP_HOST} (sompattern)\.domain\.com
RewriteRule ^(?!appdir/).* appdir/catchall.php?arg=$0&subdomain=%1 [L,QSA]
The (?!appdir/) bit is called a lookahead negative assertion and this stops the rule refiring on itself.
I'm pretty sure you can set vhost *.yourdomain.com to point to a single path and then use mod_rewrite for the url parsing.
Related
I've been searching lot of related tutorials and so on from Google to solve this on my own, but with zero luck. Therefore I am here to ask. I am trying to 'prettify' my project URL by rewriting. I am not sure are these all achievable anyhow, because I am just starting to get my head around the subject.
I am working 'example' on localhost project folder localhost/example. File '.htaccess' is located in that folder. Where I have set the following:
RewriteEngine On
RewriteBase /example
So basically my application now generates a URL consisting at least 1 parameter all the time and another pointing current location.
Current URL: localhost/example/admin.php?e=2&p=frontpage
Fantasy: localhost/example/admin/2/frontpage
About the parameters:
p stands for selected page
e stands for event
Okay lets think this all is achievable easily, do I have to change all the attributes to match current shown url?
Now they are:
href="?e=2&p=settings"
Should they be:
href="2/settings" ?
I am checking what value GET parameter P has, then including that page into content area.
That is pretty much it, pretty too complex for me, but for education purposes I really want to understand this thru and thru. Thank you.
EDIT:
With the added
RewriteRule ^admin.php/(.*)$ /admin.php?e=$1 [L,QSA]
I am getting lot of pathing errors, whole site is without styling and js files.
EDIT 2:
RewriteEngine On
RewriteBase /example
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule /admin.php/e=?(.*)$/p=?(.*)$ /admin.php?e=$1?p=$2 [L,QSA]
Now urls are following:
http://localhost/example/admin.php/2/inc/vex/vex.css
http://localhost/example/admin.php/2/css/modestgrid.css
It is not showing the page in url and the paths are not correct.
They should be http://localhost/example/admin.php/css/modestgrid.css
Your question is a bit vague, contradictory and it is unclear how you actually want to handle (reference) your asset files. But in general I'd say this should be a starting point to get you going:
RewriteEngine On
RewriteBase /example
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/(.*)$ $1.php?e=$2&p=$3 [END]
For this to work you obviously need the apache rewriting module to be installed and loaded, you need to take care that the interpretation of dynamic configuration files is enabled at all (AllowOverride directive) and you have to place such file in the correct location with reading permission for the http server process.
In case you get an internal server error (http status 500) for that chances are that you operate a very old version of the apache http server. In that case you probably need to replace the [END] flag with the [L] flag which probably will work here too. You will find a hint on that in your http servers error log file in that case.
And a general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only supported as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).
I want to have a single PHP file that takes care of multiple URLs in a subdirectory.
For example, my site is http://www.startingtofeelit.com/. I want one php file, say, called playlist.php which would handle when a user goes to http://www.startingtofeelit.com/playlist/101 or if they go to http://www.startingtofeelit.com/playlist/142 etc. I want to be able to strip the number (101, 142 in my example urls above) to use as a variable (the playlist ID), so I can display the correct playlist.
I know that I can create an index.php in my playlist subdirectory and use GET variables like http://www.startingtofeelit.com/playlist?id=102 and get the ID that way, but this is much sloppier looking and I'd like to be able to know how to do it the other way.
My site is built on WordPress, but I don't think this should make a difference in any way.
Well, you cannot achieve this with PHP alone.
If you use Apache, you can use .htaccess
If you use IIS, you can use URL Rewrite
The basic idea behind those modules is to mapping from one URL to another URL. For example: you would want to map from
http://www.startingtofeelit.com/playlist/142 =>
http://www.startingtofeelit.com/playlist.php?id=142
You can express the URL mapping in regular expression. For example, in .htaccess (Apache). You can write like this
RewriteRule ^playlist/([0-9]+)/?$ playlist.php?id=$1
Noted that, you need to have .htaccess file in your website directory. Since, you are using Wordpress, chance that you have existed .htaccess is high. You can simply append that line of code to existed .htaccess
The following is an explanation of the regular expression:
^playlist/ # any URL start with playlist/
([0+9]+) # following by number, and store it as $1
/?$ # end with or without /
Mapping to
playlist.php?id=$1 # where $1 is taken from the matched number from our pattern.
This is usually handled in a way similar to what you already tried. However, it's common to use a re-writing script so that your application will accept a clean URL such as:
http://www.startingtofeelit.com/playlist/142
...and re-write it for your application as such:
http://www.startingtofeelit.com/playlist?id=142
For example, if you're using an Apache web server and have the mod_rewrite module installed and enabled, you can use the following snippet in an .htaccess file and use your GET parameter as you indicated you already know how to do. Other popular web servers have unique URL re-writing modules that will let you do the same.
<IfModule mod_rewrite.c>
RewriteEngine On
# Rewrite this:
# http://www.example.com/somepage/1
# ...into this:
# http://www.example.com/somepage?id=1
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
I realize this question has been beaten to death by a lot of people asking it, but most of the answers appear to be for a very specific case that only suits their needs, and so far I have not found a suitable solution (at least, as far as i can see).
My problem is that I am trying to make my website redirect URL parameters from an ID to an actual string.
For example:
www.example.com/?category=1
would display as:
www.example.com/software
while
www.example.com/?category=2
would be displayed as:
www.example.com/software/desktop
From what I've read up, I'm supposed to be looking into an apache rewritemap, and this is where my confusion comes in. I'd really rather not have to load from a flat txt file, as I'd like to make this as dynamic as possible, and I have read that I can make it read from a php file and read it from a MySQL database, which is what I'd like.
The problem with that is that I'm really not too sure what the proper way is of achieving this. The RewriteMap document only somewhat covers flat .txt files, and not achieving it with MySQL.
So basically what I'm asking is if someone can explain how to achieve what I'm looking for, or at least point me in the right direction. Most of the threads I've found so far have sadly not been too helpful as of yet, but it's possible I might have passed by useful ones.
If it helps, right now, my MySQL data is formatted in an inherited structure like so:
ID | Title | Link | Parent
1 | Software | /Software/ | NULL
2 | Desktop Software | /Software/Desktop/ | 1
2 | Mobile Software | /Software/Mobile/ | 2
PS:
I should add that most solutions I've found give this as the example:
RewriteMap examplemap prg:/path/to/file.php
RewriteRule (.*) ${examplemap:$1}
Yet it never gives information as to what is in that file.php, and how it queries and returns the value.
EDIT
I should mention that I am on a shared hosting server, not my own private one, and so I may not have access to all possible options
EDIT 2
Just for the sake of clarity:
What I'm trying to do is make it so that a user who accesses 'example.com/software' would be treated as though they are on 'example.com/?category=1'; basically prettying the link and making it more readable. The only thing is, I'm trying to read it from a database
If you don't have access to the server or vhost config, you can't use RewriteMap anyways. The map itself needs to be defined in either the server or vhost config, not in an htaccess file. But apache 2.4 has an option of using mod_dbd to use an SQL query to define a rewrite map.
If you need to access MySQL, you're probably better off doing all of this in PHP instead of using mod_rewrite. You'd use mod_rewrite to route to your php file, which would then redirect. Maybe something like this?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /file.php?link=$1 [L]
So when someone requests http://example.com/Software/Mobile/, the request gets rewritten to: /file.php?link=Software/Mobile/, and your file.php script would do the lookup.
Or if you actually mean the other way around:
RewriteCond %{QUERY_STRING} category=([0-9]+)
RewriteRule ^$ /file.php?ID=%1 [L]
So when someone requests http://example.com/?category=2, the request gets rewritten to: /file.php?ID=2 and the php script does the lookup.
My suggestion would be to look at utilizing a front controller pattern. I think that once you start getting into user friendly URL's or the concept of "routes", that the front controller can really simply things since you no longer have to worry about mapping specific URL's to specific controllers at the web server level.
If you have Apache mod_dir enabled (chances are you do), you could do something like this in your Apache config or .htaccess:
FallbackResource /index.php
This simple directive will direct any requests that would otherwise cause a 404 error to be directed to a front controller at /index.php.
This can also be done via mod_rewrite like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [L,QSA]
In the front controller, you could evaluate the URI and route the request to whatever logic need to handle the request. You could do this via lookup of routes from a database or a hard-coded array of routes or whatever. (I would suggest however that, if using a database, you have a cached version of the routes available for quick access).
There are a number of different PHP route controllers available such that you don't need to reinvent the wheel (most every modern framework has some sort of routing concept).
I would to know how one is able to append a username directly to a site url without having to put it within a query?
Eg
www.myspace.com/micheal
instead of
www.myspace.com?name=micheal
Without having to create a new folder for the user so that when the url is typed including the name, the surfer is taken directly to the user's profile.
Thanx
If you're using Apache, which, using PHP, you most likely are, look into mod_rewrite. This lets you do things like this, where www.myspace.com/micheal would be translated internally to www.myspace.com/?name=micheal before being sent to the scripts.
Take a look here http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html for the documentation on how to use it.
For the Apache web-server .htaccess file with the following code will do the thing.
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?name=$1 [QSA,L]
This is called url rewriting, and is handled by mod_rewrite on Apache servers.
A rewrite rule takes the incoming uri, parses it and rebuilds it into what the script needs to run.
A very simple example:
RewriteRule ^michael$ /?name=michael$
There's lots on Google when you know where to look. Start here:
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
As everyone has pointed out you want URL Rewriting.
If you are using IIS rather than Apache, there are still a couple of options.
Free Option - Ionics Isapi rewrite filter
Commercial Option - Isapi_Rewrite
I think you might be referring to "Pretty URLS" which is generally setup on a web server level using something like Apache mod_rewrite:
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
http://www.roscripts.com/Pretty_URLs_-_a_guide_to_URL_rewriting-168.html
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.