Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
In the end, this was super easy to solve! It wasn't solved the way I first expected though, using .htaccess. I solved it with something called wildcard subdomain.When you register a new subdomain, enter * in the domain prefix, such as *.example.com. A folder for the wildcard subdomain will be created on your server, such as_wildcard_.example.com. Whenever you accesssite1.example.com,fakesub.example.cometc, the browser of the visitor will read the files in thewildcard.example.com folder.The beauty of it all is that if I create a certain subdomain that I want to use, for exampleforum.example.com, this real subdomain will have priority over the wildcard subdomain, and files will be fetched from the folder for this subdomain, as opposed to from the wildcard subdomain folder.I use PHP and need to know the subdomain to fetch the appropriate database for the current user. To do this, I use the following code:$subdomain = explode('.', $_SERVER['HTTP_HOST'])[0]With a wildcard SSL cert I have all of these subdomains secure. | I'd like to create fake subdomains for different users for more vanity, and to make the user (in this case a company) feel they are in a more isolated environment.For the sake of maintainability, it's important for me that all users still browse the same files, to avoid having to update files for every single user that exists when updating the code.My website has one public part at root, let's saywww.example.com. I'd like to be able to fake the following kind of subdomains:user1.example.comThe true URL would bewww.example.com/member/?user=user1. I'd like for the folder structure to follow the same pattern.www.example.com/member/settings/?user=user1would appear asuser1.example.com/settings/and so on.I assume this would best be achieved with.htaccess, no?.
What is the proper.htaccesscode for this?Thank you! | Fake subdomain for different users while still browsing same folder structure |
Assuming your host allows overrides, this may work:<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !.well-known/
RewriteRule "(^|/)\.(?!well-known)" - [F]
</IfModule> | I want to create SSL certificate for my domain via the webroot directory ".well-known/acme-challenge" for verification. I'm using shared hosting and I don't have access to apache configuration files, so I can only use .htaccess file.Problem is that I can't access files in this folder from browser using address "my.domain/.well-known/acme-challenge/filename". I'm just getting 404 error, even though I have these files in this directory.So I want to know, if there's any rule, which I could use in .htaccess file to gain access to hidden directories from browser. If you need more informations let me know. | Allowing to access files in hidden directories on Apache server (especially ".well-known" folder) |
Ok i confirmed with my hosting service, my problem was i had pound sitting in front of my server (for varnish) :-) . I switched it to haproxy and that is redirecting all my traffic to HTTPS so I don't need anything in the .htaccesss, Thank you | I have two .htaccess rules one to rewrite https:RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]and another to restrict some urls to only be accessible from whitelisted IPs:RewriteCond %{REQUEST_URI} ^/(index.php/)?admin[NC]
RewriteCond %{HTTP:X-FORWARDED-FOR} !^111.123.456.222
RewriteRule ^(.*)$ https://%{HTTP_HOST}/ [R=302,L]the second rule works fine by itself but when I add the first both i get the too many redirects error how do i get the first rule to work (on some servers it works properly)?UPDATEI am closing this question until I hear from my host if there is something in my server environment that is causing my problem | .htaccess rules to rewrite https and restirct some urls to certian IPs |
Ifdirective works on Apache 2.4 and newer versions. On lower versions you can useRewriteConddirective to conditionally rewrite urls.You can use something like thisRewriteEngine on
#if host == "www.production.com"
RewriteCond %{HTTP_HOST} ^www.production.com$ [NC]
# execute the rule
RewriteRule ^wp-content/uploads/(.*)$ https: //s3-eu-west-1.amazonaws.com/<BUCKET-NAME>/wp-content/uploads/$1 [R=301,L] | Been looking around the web to add a production rule in the.htaccessfile. I have a wordpress website; one for production and the other, staging.When a file is uploaded, it goes to AWS (s3). I need to prevent this behaviour for staging.The code that sets the asset path is, in the.htaccessfile:RewriteRule ^wp-content/uploads/(.*)$ https://s3-eu-west-1.amazonaws.com/<BUCKET-NAME>/wp-content/uploads/$1 [R=301,L]I cant seem to find an "if statement" or some sort of condition to use. Honestly, I think this is not possible. Is it?I only need to run that code for production and not staging.Staging url is different from production.UpdatedWhenever I use below, my website crashes:<If "-z req('Host') == 'www.<PRODUCTION>.com/'">
RewriteRule ^wp-content/uploads/(.*)$ https://s3-eu-west-1.amazonaws.com/<BUCKET-NAME>/wp-content/uploads/$1 [R=301,L]
</If> | Can you have a conditional in the htaccess file |
You can use it in conjunction withmod_setenvdirective as:# set variable NO_PASS if URI starts with /test/page/
SetEnvIfNoCase Request_URI "^/test/page/" NO_PASS
# Allow NO_PASS but ask for password otherwise
AuthType Basic
AuthName "My Protected Area"
AuthUserFile /Full/Path/To/passwords
Require valid-user
Satisfy any
Order deny,allow
Deny from all
Allow from env=NO_PASS | I have a site which have .htaccess password protected. Now I want to allow for some URL of the site.https://www.exampale.comis password protected.
But I don't want any password popup show forhttps://www.exampale.com/test/page/{variable}Can this possible in .htaccess file ?Need reverse ofPassword protect a specific URL | How can allow a url type from .htaccess password protection? |
Here is a Javascript code that you can use for this redirection:<html>
<head>
<title>Form Post Example</title>
<script>
function prettySubmit(form, evt) {
evt.preventDefault();
var val = form.query.value.toLowerCase();
window.location =
form.action + '/' + val.substr(0, 2) + '/' + val.replace(/ /g, '+') + '.html';
return false;
}
</script>
</head>
<body>
<form method="get" action="flowers/search" onsubmit='return prettySubmit(this, event);'>
<input type="text" name="query">
<input type="submit" value="Search">
</form>
</body>
</html>Then you can have this rule insite/.htaccess:RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^/.]+)\.html$ index.php?query=$1 [L,QSA,NC]This will convert your URLs to:http://127.0.0.1/site/flowers/search/bi/bird.htmlWhen you perform search using wordbirdin search field. | How can I change page url query and get first two letters . in .htaccess or phphttp://127.0.0.1/site/flowers/index.php?query=Bird
http://127.0.0.1/site/flowers/index.php?query=eagleLike this :http://127.0.0.1/site/flowers/search/bi/bird.html
http://127.0.0.1/site/flowers/search/ea/eagle.htmlHtaccess code :127.0.0.1/site/.htaccessRewriteEngine on
RewriteRule ([^/\.]+)/?.html$ index.php?query=$1 [L] | Changing the page URL and get first two letters |
You should useBflagin your rule, that instructs RewriteRule to escape non-alphanumeric characters before applying the transformation:RewriteRule ^Entertainment/Music/(.*)/$ ?sub=Entertainment&page=Music&e1=$1 [B,QSA,NC,L]Now when you dump$_GETarray you will get:Array
(
[sub] => Entertainment
[page] => Music
[e1] => Collections/Linkin Park/Dead By Sunrise (2009) + Album Cover
)Note appearance of+beforeAlbum Cover. | There are a lot of similar questions here, but I have found none to help me.
Basically, i have a string like this:Collections/Linkin Park/Dead By Sunrise (2009) %2B Album CoverThe string is part of a longer url, and this specific part gets assigned to the $_GET array, through a .htaccess RewriteRule. When I echo the string stored in $_GET, I get:Collections/Linkin Park/Dead By Sunrise (2009) Album CoverThe %2B just disappears (In the webpage source, it shows three spaces). Why is that? And how can I prevent it?It's only an error with +. I know php treats + as a space, but it shouldn't when it's encoded. | PHP: Encoded + is replaced with space |
Just an idea, if you have two subdirectores, e.g.deanden, you could rewrite instead of redirect based onAccept-Languageheader. But if the browser requests an explicit path including the language prefix, it won't be redirected.http://www.example.com/page1.htmlwill show/en/page1.htmlor/de/page1.htmldepending onAccept-Languagehttp://www.example.com/en/page1.htmlwill always show/en/page1.htmlno matter whatAccept-LanguagesaysYou could try these (untested!) rulesRewriteRule ^en/ - [L]
RewriteRule ^de/ - [L]
RewriteCond %{HTTP:Accept-Language} ^de [NC]
RewriteRule ^ /de%{REQUEST_URI} [L]
RewriteCond %{HTTP:Accept-Language} ^en [NC]
RewriteRule ^ /en%{REQUEST_URI} [L]Another approach could be to set a cookie, when the user decides on a language, and deliver pages according to this cookie. | following problem:
I have 2 html sites in subfolders, one site in English and one in German. I use .htaccess rewrite rule to redirect to the right site based on the language of the user:RewriteCond %{HTTP:Accept-Language} ^de [NC]
RewriteRule ^$ http://example.com/ [L,R=301]This is the code in the .htaccess in the subfolder of the English version.
The problem occurs when a German user wants to view the English version of the page, he always gets redirected to the German version.Is there any way to redirect the user on the first visit, but when he clicks on the hyperlinkEnglishon the German page, he gets to see the English version, without being redirected again to the German site?mod-rewrite is available but I need a condition to redirect only once (on first visit) and when the user clicks a specific hyperlink, he wont get redirected again? | .htaccess rewrite / accept language |
In singleRewriteRuleone can do this using negative lookahead:RewriteRule ^mapname(?!/something\.php/allow/this/uri/?$) - [F,L,NC] | I want to deny access to urls starting with/mapname, so that urls like/mapname/mapname2and/mapname/file1etc, are blocked. But there is 1 url that I want to allow, for example/mapname/mapname.php/something/something/something.php/something. How do I do this using htaccess?To deny access I used the following code example. This worked, but I can't figure out how to allow specific urls.RewriteCond %{REQUEST_URI} /mapname
RewriteRule ^.*$ / [R=301,L] | htaccess deny access specific url but with 1 exception |
You can use this rule to rewrite/article/foo/barto/article?aid=foo&aname=barAdd the following right bellowRewriteEngine onRewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^article/([^/]*)/([^/]+)/?$ /article?aid=$1&aname=$2 [L,QSA,B] | I am working on a PHP application, in which I need to use forward slash in place of question mark in get request. Like:www.example.com/article?aid=10&aname=my-articleshould be changed towww.example.com/article/10/my-articleFollowing is my .htaccess:Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/$1 [R=301,L]
# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/$1 [R=301,L]
# Resolve .php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^articles/(.*)$ articles?q=$1 [L,QSA,B]I have tried a lot, but not able to find solution. How can this can be done? | How to send get request with forward slash instead of question mark? |
You need to exclude the destination you are rewriting to :<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /apply/
RewriteRule ^$ webroot/ [L]
RewriteCond %{REQUEST_URI} !^/webroot/
RewriteRule (.*) webroot/$1 [L]
</IfModule>Otherwise you will get a rewrite loop error, because /webroot/ also matches the pattern (.*) | I am receiving the below error message in my Apache log after cloning the git repo on our dev server;Request exceeded the limit of 10 internal redirects due to probable
configuration error. Use 'LimitInternalRecursion' to increase the
limit if necessary. Use 'LogLevel debug' to get a backtrace.2x .htaccess copied below;Webroot .htaccess (located in projectRoot/webroot/)<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /apply/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>Application .htaccess (located in projectRoot/)<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /apply/
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]
</IfModule>Other answers say to changeRewriteBaseto/, but this isn't an option for me as I need it to be/apply/.
A few other answers pointed to theRewriteRulebeing the issue, however removing these doesn't solve the issue. | Request exceeded the limit of 10 internal redirects - .htaccess |
You can use:RewriteCond %{THE_REQUEST} /index\.php\?page=([^\s&]+)--([^\s&]+) [NC]
RewriteRule ^ /%1/%2? [L,R]And if you need in the other direction:RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?page=$1--$2 [L] | If an user clicks on these links or write these links in the address bar, I would like to force rewriting.Is it possible ?index.php?page=admin--indextoadmin/index...index.php?page=team--createtoteam/createThanks | How to force rewrite url? |
I was able to make it work with PHP and htaccess!Instead of using gulp-connect-php to create the vhost, I used XAMPP. I then target the proxy to the XAMPP vhost. Here's how I did it:gulp.task('serve-php', ['styles', 'fonts'], () => {
const proxy = httpProxy.createProxyServer({});
browserSync({
notify: false,
open: true,
port: 9000,
server: {
baseDir: ['.tmp', 'app'],
routes: {
'/bower_components': 'bower_components'
},
middleware: function (req, res, next) {
var url = req.url;
if (!url.match(/^\/(styles|fonts|bower_components)\//)) {
proxy.web(req, res, { target: 'http://xamppvhost.dev' });
}
else {
next();
}
}
}
});
gulp.watch([
'app/**/*.html',
'app/**/*.php',
'app/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});I removed phpConnect.server() and changed the proxy.web() to target my XAMPP vhost.Now everything's working!! | I'm currently using theYeoman Generator Gulp-Webapp, which I modified slightly to make it work with PHP. I simply added gulp-connect-php & http-proxy then edited the gulpfile.babel.js browserSync task by adding the following code. Now I would need tofind a way to make it work with htaccess. Any idea how this could be done?gulp.task('serve-php', ['styles', 'fonts'], () => {
phpConnect.server({
port: 9001,
base: 'app',
open: false
});
const proxy = httpProxy.createProxyServer({});
browserSync({
notify: false,
open: true,
port: 9000,
server: {
baseDir: ['.tmp', 'app'],
routes: {
'/bower_components': 'bower_components'
},
middleware: function (req, res, next) {
var url = req.url;
if (!url.match(/^\/(styles|fonts|bower_components)\//)) {
proxy.web(req, res, { target: 'http://127.0.0.1:9001' });
}
else {
next();
}
}
}
});
gulp.watch([
'app/**/*.html',
'app/**/*.php',
'app/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
}); | Browser Sync - PHP and htaccess? |
Use :RewriteEngine On
RewriteRule ^([0-9]+)/([^/.]+)/([^/.]+)/?$ /index.php?id=$1&category=$2&title=$3 [QSA,L]And add this code to yourhtml <header>:<base href="/">OR<base href="http://www.domain.com/">To fix relative css and js links | I'm trying to convert my app links, so that a link like this:http://localhost/index.php?id=13&category=Uncategorized&title=just-a-linkgets converted to this:http://localhost/13/Uncategorized/just-a-testso far I was able to do it using:RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ /index.php?id=$1&category=$2&title=$3 [QSA,L]but that completely breaks links to css and other files as it redirects every request with query to index.phpso I changed it slightly so that it only runs when the first query is a number:RewriteEngine On
RewriteRule ^([0-9]*)/([^/]*)/([^/]*)$ /index.php?id=$1&category=$2&title=$3 [QSA,L]this one doesn't break css and js files, however when you go to the link for examplehttp://localhost/13/cat/testthen try to go to another link likehttp://localhost/19/Uncategorized/somethingby clicking on it inside the previous pageit will instead redirect you to something likehttp://localhost/13/Uncategorized/19/Uncategorized/just-a-testHow do I achieve what I described without any of these weird side effects?? | mod_rewrite issues and php |
Network tab filters query based on request type, not mime type. As you request it as document (simple http get request in browser, not for example from image or styles tag), then it shows it as type=document.
Seehttps://developers.google.com/web/tools/chrome-devtools/network/referencefor more info. | I'm trying to determine the mime type of a file. In Firefox, it showstext/cache-manifest. In Chrome,F-12 -> Network Tabit shows undertypeasdocument. When I view the response headers, it never showsContent-Typeso maybe my server isn't sending it? Or am I interpretingdocumentwrong?In .htaccess, I have:AddType text/cache-manifest .manifestEDIT: I have also tried the below code and it still shows type asdocumentin Chrome:manifest.php<?php header("content-type: text/cache-manifest");?> | How view mime type in Chrome? It's showing "document" under "Network" tab |
You can use this rule in yourDOCUMENT_ROOT/.htaccessfile:RewriteEngine On
RewriteRule ^(cocacola)/.+$ /$1 [L,NC] | I want to remove (redirect or substitute) last part of url.For example, I wantwww.example.com/cocacola/anythingto bewww.example.com/cocacolasowww.example.com/cocacola/123 or www.example.com/cocacola/cat ...etcis to bewww.example.com/cocacolaI was trying hard to figure out this, but still did not find proper solutionThis is what I've triedRewriteRule ^(cocacola)\(.+)$ http://example.com/cocacola [R=301,L,NC]How to write .htaccess file to solve the question above? | .htaccess - how to remove last part of url? |
Try :RedirectMatch ^/home/(.*)$ http://anumuhammad.net/$1 | I have moved my site subfolder to root. "http:// anumuhammad .net/home" to "http:// anumuhammad .net/"This site have lot of backlink url and I need all old url redirected to new url:http:// anumuhammad . net/ home /article/212-2015-07-04-14-14-20
to
http:// anumuhammad . net/ article/212-2015-07-04-14-14-20http:// anumuhammad . net/home/article/ to http:// anumuhammad . net/article/http://anumuhammad.net/home/books/tohttp://anumuhammad.net/books/"home" should be remove when visitor came from old backlink. I have searched lot but could not found a solution that help me.This is addon website in apache server.Any help will be greatly appreciated.ThanksJulash | Rewrite old subfolder url |
This is most likely because you're running an https redirect (or another redirect) inside another .htaccess file. So it is asking for the authentication once in http, and once in https. If you do this:<If "%{HTTPS} == 'on'">
AuthType Basic
AuthName "Password Area"
AuthUserFile "/yourdirectory/.htpasswd"
<IfVersion >= 2.4>
AuthMerging And
</IfVersion>
Require valid-user
</If>then it will only ask for the password once the redirect has happened. Otherwise, get rid of the second redirect. | I use .htaccess to ask for credentials to access members only data. The .htaccess file is stored in one of the directories and protects everything in directories below it. The .htaccess file itself is very simple:AuthName "Members Area"
AuthType Basic
AuthUserFile /home/xxxxx/public_html/xxx/data/.htpasswd
require valid-userProblem is, when we moved to a new server (and built the new website within that directory using WordPress), the Authentication Box now comes up twice and requires users to enter the same correct login information both times.I've read in other strings here about trailing/, but since I don't have a redirect or anything else in my .htaccess, I'm not quite sure what to do.Anybody have any suggestions on a workaround or rewrite? | .htaccess requests correct login twice with .htpasswd and wordpress |
To enforce bothhttp://andwww.in same rule you can use this code in root .htaccess:RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} on
RewriteRule ^ http://www.example.com%{REQUEST_URI} [R=301,L,NE]To show a custom message for 404 (page not found) error use:ErrorDocument 404 "<html><head><META http-equiv="refresh" content="10;URL=/><head><body><h1>The page you were looking for doesn't exist</h1></body></html>"in the same.htaccess. This message will be displayed for 10 seconds and then browser will redirect to home page.Make sure to test this after clearing your browser cache. | SummaryI have bought a domain (Suppose (www.)mydomain.com). And I have 3 hopes: First, when user enter mydomain.com in the address bar, it can redirect to www.mydomain.com (add www. in front of the address automatically). Second, due to the domain I bought doesn't support SSL, so when user enter https:// in front of the address, directly transform it into http://. Third, when user enter the URL that doesn't exist, show the message: “The page you were looking for doesn't exist.” and redirect to my homepage (www.mydomain.com/) after 10 seconds.My tryI have searched the Internet but just found the solution of adding www. in front of the address automatically. And below is result.RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]QuestionsIs there any error in the result I found above?Is there any better way to improve the result I found above?How can I transform https:// into http:// when user enter https:// in front of the address?When user enter the URL that doesn't exist, how to show the message: “The page you were looking for doesn't exist.” and redirect to my homepage (www.mydomain.com/) after 10 seconds? | How to use .htaccess to redirect non-www to www? (Two more questions...) |
A single rule can handle both redirects:RewriteRule ^/?(index\.php)?$ /home [NC,L,R=301] | I can redirectwebsite.com/index.phptowebsite.com/homebut I can't find a way to redirectwebsite.comtowebsite.com/homeI have triedRewriteRule ^/$ /home [R=301]but it does nothing. | How to redirect website.com/ and website.com/index.php to another page with htaccess |
Try this rule:RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{THE_REQUEST} !/(robots\.txt|sitemap\.xml)\s [NC]
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,NE,R=302]Test this out in a new browser. | Hey Stack Overflowers.I have been stumped and cannot get this correct, I just want to exclude two files, in the root directory, robots.txt and sitemap.xml from https. The rest of the site over https, no problem. I got this:# Forcing HTTPS
# RewriteCond %{SERVER_PORT} !^443$
# RewriteCond %{REQUEST_URI} !^sitemap.xml$
# RewriteCond %{REQUEST_URI} !^robots.txt$
# RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [L]Which clearly results in redirect loops etc. So... any help for an htaccess noobie? | htaccess exclude sitemap.xml and robots.txt from https |
In the.htaccessfile, add the line:SetEnvIf X-Forwarded-Proto https HTTPS=on | Im using this .htaccess to add date,hour,minutes at end of my url example:example.com/pagename?201502201855It works in all my posts and pages but if i navigate to page number 2,3,4,5,6 exampleexample.com/page/2/?201502211929then i get error: This webpage has a redirect loop Error code: ERR_TOO_MANY_REDIRECTS# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(?!wp-admin)^(?!wp-login.php) %{REQUEST_URI}?%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}%{TIME_HOUR}%{TIME_MIN} [L,R=302,NE]
RewriteCond %{TIME_YEAR}%{TIME_MON}##%{QUERY_STRING} ^([^#]+)##\1
RewriteCond %{TIME_YEAR}%{TIME_MON}%{TIME_DAY}%{TIME_HOUR}%{TIME_MIN}##%{QUERY_STRING} !^([^#]+)##\1
RewriteRule ^(?!wp-admin)^(?!wp-login.php) %{REQUEST_URI}?%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}%{TIME_HOUR}%{TIME_MIN} [L,R=302,NE]
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule> | .htaccess - ERR_TOO_MANY_REDIRECTS |
Inhttpd.conf, have you thelinewhere there is:#LoadModule rewrite_module modules/mod_rewrite.soIf yes, remove the#.Maybe youhave to createavirtualhost with an alias for your local application.Follow this linkherein this case.Maybe you have already a virtual host and aliases who need to be disabled. Check in your files(hosts files, conf files etc...). | I've a problem with Wamp Server and URL Rewriting.
I've import my project from production server with his.htaccess.
The URL Rewriting work fine on production, but not in localhost.In my Wamp configuration,rewrite_moduleis activate. In the httpd.conf :<Directory "c:/wamp/www/">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.4/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# AllowOverride FileInfo AuthConfig Limit
#
AllowOverride all
#
# Controls who can get stuff from this server.
#
# onlineoffline tag - don't remove
# Require local
Allow from all
</Directory>But, on my website, the linkhttp://localhost/conditionsreturn an 404 error.
My .htaccess :Options +FollowSymlinks
RewriteEngine on
# Conditions
RewriteRule ^conditions pages/conditions.php [L]All files are in the wamp's root (c:/wamp/www/).Help :( | URL Rewriting not work on Wamp Server |
You can have a new rule like this:<IfModule mod_rewrite.c>
RewriteEngine On
# handle home page
RewriteRule ^/?$ home [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 index.php
</IfModule> | I am currently using a custom MVC Architecture to create my website.The problem is that when I enter localhost/website/ which in the future would be www.website.com/, I want my homepage to be shown. Currently I am making this work by using localhost/website/home/ but I don't want that, I just want localhost/website/ which automatically shows the homepage.I have tried to do this with htaccess, but without any success. When I navigate to localhost/website/ it shows me an error 'This webpage is not available'.My htaccess code: This is found inside my public folder.<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
</IfModule>
<IfModule !mod_rewrite.c>
ErrorDocument 404 index.php
</IfModule>I hope that made some sense and that someone could help me.Thanks | MVC URL Redirect |
According to Bluehost, you have to select your PHP version in the control panel. Depending how they set Apache up, you may not be able to select what version of PHP you run via.htaccessAll our servers support (i.e. are capable of running) PHP 5.2 and PHP 5.4. The default version is 5.4.x but you can follow the directions below to use PHP 5.2.X instead. However we are working on phasing out PHP 5.2.x from our servers as it is no longer supported by its developers. | I would like to load a specific PHP version (5.4), I use Bluehost shared hosting which uses Apache and support PHP 5.4.I have a.htaccessfile and aphp.inifile in a subdirectory (/api) with that line:AddHandler application/x-httpd-php54 .phpto specify to server to use PHP 5.4.I have in/public_htmlanother htaccess which usessingle php.ini filewhich is located in that directory.I have a file called by Shell, with that hashbang line:#!/usr/bin/php -c/homex/xx/public_html/api/php.iniI've looked at PHP version at runtime(when called by hashbang line), it shows5.2(default version) despite of the fact that I specified to use PHP 5.4 and the usage of php.ini in/api.In the other hand, if I call my script by abrowser, PHP version used is5.4.What's wrong? Do I need to add something else?How could I use PHP 5.4 with my hashbang called file?I've deleted php.ini file from/apiand deleted that line fromAddHandler application/x-httpd-php54 .php.htaccess file. So the php.ini file used is the single one from/public_html.I've alo added that line to .htaccess from/public_html:AddHandler application/x-httpd-php54s .phps which mean single php.ini file. | Load specific PHP version |
You can try:<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} /(code|tmp) [NC]
RewriteRule ^ - [L]
RewriteRule ^((?!public/).*)$ public/$1 [L,NC]
</IfModule> | Here is my Directory Structurelocalhost or livehost
-app
-bootstrap
-public
-vendor
-code
-demoHere is my .htaccess<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
RewriteRule ^(.*)$ public/blog/$1 [L]
</IfModule>Here is my routeRoute::get('/', 'Sys@Home');
Route::get('blog', 'Sys@Blog');
Route::get('contact', 'Sys@Contact');To access these , I don't want to enter my url aslocalhost/public/
localhost/public/blog
localhost/public/contactInstead its enough to enter aslocalhost
localhost/blog
localhost/contactAt the same time, it should not apply to these to folders/codeand/demoto access the directory.So I got to write exception to these directories from this question.htaccess exception to particular folders<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule %{THE_REQUEST} /code
RewriteRule %{THE_REQUEST} /temp
RewriteRule ^ - [L]
RewriteRule ^(.*)$ public/$1 [L]
RewriteRule ^(.*)$ public/blog/$1 [L]
</IfModule>After applying this I can able to access the folderlocalhost/codeandlocalhost/demoBut I can't able to access the folder likelocalhost
localhost/blog
localhost/contactHow can i make it both possible ? | .htaccess exception makes issue on main directory |
The URL is decoded before it is sent through the rewrite engine, so you need to match against@, and not the encoded string. Try:RewriteRule ^test/([-_.@A-Za-z0-9]+)/?$ test.php?variable=$1 | So I'm trying to pass a PHP urlencode() variable through a mod_rewrite rule, but I can't seem to get it working correctly.Currently I'm passing this sort of thing:/test/abc%40test.co.ukThe @ symbol replaced with the &40 in the urlencode.Through this rule:RewriteRule ^test/([-_.%A-Za-z0-9]+)/?$ test.php?variable=$1As far as I'm aware this should allow the % symbol through; why isn't it working? Am I missing something obvious? | Allow percentage (%) symbol in mod_rewrite? |
You can check query string withmod_rewriteRewriteEngine On
RewriteCond %{QUERY_STRING} ^one=two&three=3&44=1$ [NC]
RewriteRule ^first/second/$ /? [R=301,L] | I have bad url:http://mypage.org/first/second/?one=two&three=3&44=1and i want this redirect to:http://mypage.orgbut in htaccess:Redirect 301 /first/second/?one=two&three=3&44=1 http://mypage.orgnot working. For example:Redirect 301 /first/second http://mypage.orgworking ok. | How to redirect 301 bad url? |
This is possible ifmod_proxyis enabled in your Apache config.Oncemod_proxyandmod_rewriteare enabled place this rule in yourDocumentRoot/.htaccessfile ofsitehosthost:RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?sitehost\.com$ [NC]
RewriteRule ^ http://www.mainsite.co.uk%{REQUEST_URI} [L,P]Pflag is used for proxying the request to external URL. | Am trying to do the following. My website is hosted onwww.sitehost.com/ukBut I own this domain.www.mainsite.co.ukIs it possible to redirect the user hitting www.mainsite.co.uk to www.sitehost.com/uk but retain the www.mainsite.co.uk?I tried doing .htaccess redirect and it worked but it changed the URLs from www.mainsite.co.uk to www.sitehost.com/ukIdeally it would work like so...www.sitehost.com/uk/post/20can be accessed viawww.mainsite.co.uk/post/20I tried mod_proxy but it didn't seem to work all the way. Anyone know how to do this? Is this even possible with Apache? | URL Mask/Cloak with redirect |
ProblemThe problem is with your understanding of theQSAflag. What that does is appends the original query string to the redirected URL. This is useful in some circumstances where you wish to append another parameter (or more than one) to the query string.**Example**Given the URL:http://example.com/?var1=somevalueThen the rewrite rules:RewriteRule . /?var2=thisvalue
RewriteRule . /?var2=thisvalue [QSA]Would output:Rule 1 > http://example.com/?var2=thisvalue
Rule 2 > http://example.com/?var2=thisvalue&var1=somevalueThe problem, in your case is that you don't want to append the query string as a query string you want to append it as a variable; if that makes sense...SolutionThe solution then is - as simple as it sounds - to append the query string as a variable...You can do this with the use of the variable%{QUERY_STRING}:RewriteEngine On
RewriteBase /
RewriteRule ^(.*) index.php?processurl=/$1?%{QUERY_STRING}SuggestionAs anubhava pointed out you might like to add:RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-dSo that you don't accidentally wind up rewriting the wrong urls.RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?processurl=/$1?%{QUERY_STRING} | I'm trying to rewrite the followinghttp://example.com/somefile?variable=somevariabletoindex.php?processurl=/somefile?variable=somevariableI understand I need to use [QSA] to pass the variables so I have written the following in my htaccess:RewriteEngine On
RewriteBase /
RewriteRule ^(.*) index.php?processurl=/$1 [QSA]However this RewriteRule doesn't seem to be passing the variable. All I get is index.php?processurl=/somefile | Passing variables through htaccess with a rewrite rule |
I find the solution , It is the problem of apache rewrite_module. I changed my httpd.conf file and now its working perfect.ChangeAllowOverride NonetoAllowOverride All<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>and Restart the Apache daemon using putty# service httpd restartReference Url : -http://dev.antoinesolutions.com/apache-server/mod_rewrite | i am new in php & codeigniter.i am working on a project which was running in a serverabcd.comand i am using htaccess code like thisRewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]now my project has been moved to another server192.000.000.000.i can access the login page, when the user is logged in session is getting set and it is redirecting to192.000.000.000/myproject/userand here i am getting 404 errori have been set base_url in config.php is like this$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['index_page'] = '';my WINSCP Project structureold one : /home/my_org/public_html/prjFolder
new one : /var/www/html/prjFoldermy .htaccess file like thissystem/
application/
user_guide/
index.php
.htaccessif anyone find solution please help me.. | htaccess not redirecting in codeigniter |
first you have to locate your errorpagei.e. on local server my 404.php in root/error thenErrorDocument 404 /error/404.phphere first slash is root of serveryour server could not find 404.php thats problem so locate your 404.php | I am using .htaccess in my project, i just use the following codeErrorDocument 404 /404.phpin the .htaccess inside the root folder, but it does not redirect to 404.php while trying to open the misspelt webpage.I want to know whether there is syntax error in the .htaccess file.I used .html file instead for .php file. but it throws the same error.Not FoundThe requested URL /ht/re was not found on this server.Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. | Usage of .htaccess for 404 error |
You can use this combined .htaccess:# require valid user only on /admin
SetEnvIf Request_URI ^/admin(/|$) auth=1
# if(test.example.com) { require valid user on all domain }
SetEnvIf Host ^test\.example\.com$ auth=1
# if(localhost) { do nothing }
SetEnvIf Host ^localhost$ !auth
AuthUserFile mypasswordfile
AuthType Basic
AuthName "Enter a password"
Order Deny,Allow
Deny from all
Allow from env=!auth
Require valid-user
Satisfy any | I need to protect different par of my website depending on the environment I'm working on.
I have three different environments:localhost : protect nothingwww.test.example.com : protect the whole website (it's a test website so I don't want it to be accessible)www.example.com : protect only /admin url (the live website, only /admin is protected)For now, I use different htaccess files.For test.example.com, I add:AuthUserFile mypasswordfile
AuthType Basic
AuthName "Enter password"
require valid-userFor example.com, I add:SetEnvIf Request_URI /admin/? auth=1
AuthUserFile mypasswordfile
AuthType Basic
AuthName "Enter a password"
Order Deny,Allow
Deny from all
Allow from env=!auth
Require valid-user
Satisfy anyIs there a way to use only one htacess with condition to have something likeif(localhost) { do nothing }
if(test.example.com) { require valid user on all domain }
if(example.com) { require valid user only on /admin} | 3 htaccess protection rules on 3 different environments |
You may not needR=301here to hide actual PHP handler.Try this rule withRewriteBase:RewriteEngine on
RewriteBase /companytools/podcasts/
RewriteRule ^(.+?)\.mp3$ test.php?file=$1 [L,QSA] | I need to create a rewrite to take traffic going to mp3/mp4 files in a specific subdirectory and then route them to a PHP file that tracks download stats etc before routing them to the actual file location since iTunes requires your podcast RSS contain actual media file extensions (.mp3, .mp4, etc)I have created rewrites before with no problem but now I am running into an odd issue on this company's server.My .htaccess located at www.company.com/companytools/podcastsRewriteEngine on
RewriteRule ^/(.*).mp3$ /test.php?file=$1 [r=301,L]Right now it is partially working it does act upon the mp3 file but ends up including the full path to test.php after the domain, so I end up with a 404 page looking for this URL:www.company.com/www/internal/docs/companytools/podcasts/test.php?file=testbasically I need the path, but only the /companytools/podcasts part.Any help is appreciated. | mod_rewrite inserting full path to file |
Have your complete.htaccesslike this:Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]
RewriteCond %{THE_REQUEST} \s/+products(?:\.php)?\?id=([0-9]+) [NC]
RewriteRule ^ products/%1? [R,L]
RewriteRule ^products/([0-9]+)/?$ products.php?id=$1 [L,QSA]
## hide .php extension snippet
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} \s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L] | i have tried lots of for url rewrite rules in htaccess but i am stuck now. i have to change this urlproducts.php?id=31toproducts/31i have usedOptions +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]
## hide .php extension snippet
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]using this i get the following result:products?id=31But this isn't working. Any ideas? | Remove .php and id from url and replace with slash |
Try these rules on top of your other rules:RewriteCond %{THE_REQUEST} \s/blog/([^\s]*) [NC]
RewriteRule ^ http://blog.domain.com/%1 [L,R=301]
RewriteCond %{HTTP_HOST} ^blog\.domain\.com$
RewriteRule !^blog/ blog%{REQUEST_URI} [L,NC] | I'm trying to find an answer on different places, but I can't find the full solution for this.I had a folder setup for a blog. Now we move to an subdomain setup. The redirect shown below works perfectly. The only thing that doesn't work is when the url is a subdomain combined with folder. that isn't redirected.RewriteCond %{HTTP_HOST} ^(www\.)domain\.com$
RewriteRule ^blog/(.*)$ http://blog.domain.com/$1 [L,R=301,QSA]
RewriteCond %{HTTP_HOST} ^blog\.domain\.com$
RewriteCond %{REQUEST_URI} !blog/
RewriteRule ^(.*)$ blog/$1 [L,QSA]www.domain.com/blog/some-url-here is redirected to
blog.domain.com/some-url-hereWhen I try blog.domain.com/blog/some-url-here it returns a http-status of 200 and when I try to redirect I get a infinitive loop.Is there a redirect that I've missed? | .htaccess how to redirect subdomain/folder to subdomain only |
People looking for a complete solution:Must Ass FilesMatch "^.*$" line to ip's to blockAdd ^ to the front of the FilesMatch for the allowed filesFinished Code:DirectoryIndex index.php index.html 403.php
ErrorDocument 403 /403.php
<FilesMatch "^.*$">
order allow,deny
allow from all
deny from 5.39.218
deny from 146.0.74
deny from 5.39.219
deny from 176.102.38
</FilesMatch>
<FilesMatch "^(|403\.php|hero\.jpg)$">
order allow,deny
allow from all
</FilesMatch> | I'm blocking a few IP addresses using the htaccess technique and this works well for all my pages except for the site/document root where the Fedora Core Test Page is displayed instead.I'm aware that the test page is shown when no document in the root directory is found, thus I have created multiple documents and set the directory index, where index.php is my regular document root file.N.B. I don't have access to /etc/httpd/conf.d/welcome.confBelow is the related htaccess code:DirectoryIndex index.php index.html 403.php
ErrorDocument 403 /403.php
order allow,deny
deny from 5.39.218
deny from 146.0.74
deny from 5.39.219
deny from 176.102.38
allow from all
<FilesMatch "(403.php|hero.jpg|index.html)$">
order allow,deny
allow from all
</FilesMatch>Is there a way of displaying my custom 403 page for the website root?Any suggestions would be much appreciated. | Custom 403 Error Page in Root Directory |
Use it like this:RewriteEngine On
RewriteRule ^(register)/?$ /login.php?page=$1 [NC,L,QSA] | I want to rewrite a url to static query as:example.com/register => example.com/login.php?page=registerI'm using this:RewriteRule ^register login.php?page=register [NC,L] | Rewrite URL using .htaccess with a static query string |
Enablemod_rewriteand.htaccessthroughhttpd.confand then put this code in yourDOCUMENT_ROOT/gaggletrips/.htaccessfile:Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /gaggletrips/
RewriteRule ^(groups)/([^/]+)/?$ $1/index.php?name=$2 [L,QSA,NC]Once these rules are in place you can directly typehttp://mysite.com/groups/test_groupand it will loadhttp://mysite.com/groups/index.php?name=test_groupbehind the scenes without changing URL in the browser. | The users can create their own group in my site.They can create with their desired group name.That is, "http://mysite.com/groups/"_______--Ex:http://mysite.com/groups/test_group('http://mysite.com/groups/' is default then the users can add the their desired name and i have maintained with unique name).I have one index.php in 'groups' directory.Idont wantto access with "http://mysite.com/groups/index.php?name=test_group"...Iwant to accesswith "http://mysite.com/groups/test_group"How to achieve it without mention theindex.phpwith parameter segment in Core PHP?Thanks in advance... | Adding the Group Name in URL and Accessing that URL without index Page |
As perApache Manual subrequest is:a page which is included using an SSI (Server Side Include) is a subrequest, and you may want to avoid rewrites happening on those subrequests. Also, when mod_dir tries to find out information about possible directory default files (such as index.html files), this is an internal subrequest, and you often want to avoid rewrites on such subrequestsSo to get value of%{IS_SUBREQ}=truehave a RewriteRule like this:DirectoryIndex index.php
RewriteEngine On
RewriteCond %{IS_SUBREQ} true
RewriteRule ^index\.php$ $0?s=%{IS_SUBREQ} [L]Then visit your website by opening this URL:http://site.com/Then inside/index.phpif you dump$_GET['s']you will see valuetrue. | Does anyone knows when IS_SUBREQ variable is "true"? Everything, that i've tried, gave me only "false".Info from apache docsIS_SUBREQ
Will contain the text "true" if the request currently being processed is a sub-request, "false" otherwise. Sub-requests may be generated by modules that need to resolve additional files or URIs in order to complete their tasks.Could anyone show me some example when IS_SUBREQ is "true"?Some of what i tried:
subreq.php - page with onlyTesting browser's subrequest for image (I know that server doesn't care about it, but tried)RewriteCond %{IS_SUBREQ} true
RewriteRule (.*)\.png$ nullTesting internal redirectsRewriteRule subreq\.php$ \tmp
RewriteCond %{IS_SUBREQ} true
RewriteRule tmp$ /index.htmlNo effect. | Apache IS_SUBREQ variable |
You could add anotherRewriteCondto check for%{REQUEST_URI} !^/no-mobile/.*$and then rewrite/no-mobile/to/. This will allow users on a mobile that want to view the full site to have a link to/no-mobile/.Alternative PHP SolutionIf your client wants a way to allow mobile users to use both, you can use php. Do your sameHTTP_USER_AGENTcheck in PHP and redirect the user when the hit your site.If they click aFull Sitebutton, you should redirect them to something like/force-desktopwhere you set$_SESSION['no_mobile'] = true. You can then incorporate this into your initial mobile check like so:full-site.php:<?php
session_start();
$_SESSION['no_mobile'] = true;
header('Location: /mobile');
die();then a check when a page is loaded on your site (you'll have to do it on ever page, sadly):if($is_mobile === true && !isset($_SESSION['no_mobile']){
header('Location: /mobile');
die();
} | I successfully set up mobile redirect directory based on device but the client wants a link back to the full site.RewriteEngine on
Options +FollowSymlinks -MultiViews
RewriteBase /
RewriteCond %{HTTP_HOST} ^mysite.com$ [NC]
RewriteCond %{REQUEST_URI} !^/mobile/.*$
RewriteCond %{HTTP_USER_AGENT} **{mobile dectection code I removed for this post}**
RewriteRule ^(.*)$ /mobile/ [L,R=302]I put a .htaccess file with rewritengine off into the directory of the mobile website.Any idea what rewrite conditions to use when both the mobile and main website use the same domain? Alternatively, would this be easier if I made a separate domain for the mobile website? | How do I enable my mobile website to bypass mobile redirect? |
But you have:/etc/apache2/mods-available/userdir.conf: AllowOverride FileInfo AuthConfig Limit IndexesAlthough this is related to the userdir configuration, theFileInfooverride is the bare minimum for apache to read htaccess files, within that context.In theAllowOverride documentation, we have:FileInfoAllow use of the directives controlling document types (DefaultType, ErrorDocument, ForceType, LanguagePriority, SetHandler, SetInputFilter, SetOutputFilter, and mod_mime Add* and Remove* directives, etc.), document meta data (Header, RequestHeader, SetEnvIf, SetEnvIfNoCase, BrowserMatch, CookieExpires, CookieDomain, CookieStyle, CookieTracking, CookieName), mod_rewrite directives (RewriteEngine, RewriteOptions, RewriteBase, RewriteCond, RewriteRule), mod_alias directives (Redirect, RedirectTemp, RedirectPermanent, RedirectMatch), and Action from mod_actions.When theAllowOverrideis anything except "None", the htaccess file will be read and depending on the override options, certain statements in the htaccess file will be honored. It just so happens that theFileInfooption covers a lot of the frequently used directives in an htaccess file. | Well, this is not a problem yet, but I don't understand why Apache is reading the.htaccessfiles... I do:grep -R "AllowOverride" /etcand I have:/etc/apache2/apache2.conf:# for additional configuration directives. See also the AllowOverride
/etc/apache2/sites-available/default: AllowOverride None
/etc/apache2/sites-available/default: AllowOverride None
/etc/apache2/sites-available/default: # AllowOverride None
/etc/apache2/sites-available/default:# AllowOverride None
/etc/apache2/sites-available/default-ssl: AllowOverride None
/etc/apache2/sites-available/default-ssl: AllowOverride None
/etc/apache2/sites-available/default-ssl: AllowOverride None
/etc/apache2/sites-available/default-ssl: AllowOverride None
/etc/apache2/conf.d/security:# AllowOverride None
/etc/apache2/conf.d/localized-error-pages:# AllowOverride None
/etc/apache2/mods-available/userdir.conf: AllowOverride FileInfo AuthConfig Limit Indexes
/etc/apache2/mods-available/alias.conf: AllowOverride None
/etc/apache2/sites-enabled/000-default: AllowOverride None
/etc/apache2/sites-enabled/000-default: AllowOverride None
/etc/apache2/sites-enabled/000-default: # AllowOverride None
/etc/apache2/sites-enabled/000-default:# AllowOverride None
/etc/apache2/mods-enabled/alias.conf: AllowOverride None
grep: /etc/blkid.tab: No such file or directorySeems I have no AllowOverride all, so why is it working? | AllowOverride None, and .htaccess works |
your button must not submit the form, make its type button:<button type="button" id="save" >Save</button> | I have a form and I want to add AJAX functionality to this form.Architecture: MVCI have a basic form like this:<form id="customForm" method="post">
<input type="text" id="name" name="zone_name" value="" class="input-block-level" />
<button type="submit" id="save" >Save</button>
</form>I have thisJSon myMVC-View:$('#save').click(function()
{
var name = $('#name').val();
$.ajax
({
type: 'POST',
url: 'http://localhost/myApp/process',
data: "{name:"+name+"}",
success: function (result) {
alert(result);
},
error: function () {
alert('fail');
}
});
});I have aprocessclass which is there incontrollerand have this code withinclass process {
function __construct() {
echo 'Constructor';
}
}But Doing all this gives meErrormessage through AJAX. Why is this happening? Is there any other way of doing this. Here under is snapshot:Here under is my.HTACCESSruleRewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]So when I am directly navigation to myprocessclass its working. But not with AJAX. What would be the possible reason for this?? Here under is the screenshot: | Processing PHP page using AJAX in MVC |
Add this rule on top of your .htaccess just belowRewriteEngine Online:RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?lang=(EN|DE)\s [NC]
RewriteRule ^ - [R=404,L] | I set up a new website with WordPress. But Google still has a sitelink to a no longer existing page with a URL parameter:domain.com/index.php?lang=ENwhich points to a non-existent page and should therefore throw a 404 error. But somehow WordPress does show a page statingNo blog posts have been added yet.Due to not responding with a 404 error, the site does not disappear from Google Search Results!How can I redirect incoming traffic from those two URLs:domain.com/index.php?lang=ENdomain.com/index.php?lang=DEto a 404 page? (I have set up a custom 404 page and added theErrorDocument 404in my .htaccess-file.) | Redirecting specific URL to 404 |
You need Apache >= 2.4 to make this really conditional.<If "%{HTTP_HOST} == 'mysite.local'">
# ...
</If>
<Else>
# ...
</Else>For earlier versions, this is only possible by adding a -D option to the startup command line (-DLOCAL below), then:<IfDefine LOCAL>
# ...
</IfDefine>
<IfDefine !LOCAL>
# ...
</IfDefine>(for Apache >= 2.4, see also the Define directive - same effect as adding a -D argument) | I'm trying to auto include a global.php file using htaccess. Right now I havephp_value auto_prepend_file "/local/directory/global.php"which works perfect. The problem is, I run this site both on a local server for development, and a remote web server for the live site. So obviously the /local/directory/ path is going to be variable based on whether I'm on mysite.com or mysite.local.Is there a way to say if url contains mysite.local, include this file; otherwise include this file, inside the htaccess? | .htaccess auto_prepend_file if url contains |
Just to come back at this, the proposed solution 'just works' in my case. | I've been searching for 4 hours already but I can't seem to find a solution to our problem.The problem we've encounteredWe have aCentOS Linux 6.4server, runningVirtualmin 3.99.gpl. We have a Drupal website which we would like to move to this server, and as it's a multidomain site, we will have to useFollowSymLinks. This has (as I was told) been disabled as some security flaws were discovered addressing this directive. Since then you would have to useSymLinksIfOwnerMatch. Now, Drupal has a lot of.htaccessfiles hidden deep in the roots of this system, and as I'm not sure how this new method will be supported, I wanted to ask some experts their opinion to the solution my colleague proposed.The Proposed solutionMy colleague told me that it would probably work if I'd wrote a simple shell script to edit all the .htaccess files in the root folder of the domain, which would replace all theFollowSymlinkswith theSymLinksIfOwnerMatch. As I'm not sure if this would fix this problem, I would like to ask your opinion on this.What we've triedWe've tried to fix the configuration file from Apache to allow FollowSymLinks, but this did not work. Also we tried changing the global configuration in Webmin, but webmin ignored these edits (a fix for this would be great!). Deleting the line of the .htaccess in the root folder, fixes the problem, but this is not the solution we want to use.Any other solutions, fixes or workarounds? | FollowSymLinks error "Not allowed here" |
In order to use regex better to use mod_rewrite which is more powerful than mod_alias.Enable mod_rewrite and .htaccess throughhttpd.confand then put this code in your.htaccessunderDOCUMENT_ROOTdirectory:Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
RewriteRule ^answer-now(/.*|)$ http://www.itdost.com/questions/? [L,NC,R=301] | I've a older site running in Apache Server which is already indexed in Google. I wish to redirect all those indexed links to my new site (As the older pages are not existing any more.)So i wish to redirect all my sub-sub pages to my new root pageI've pages like followshttp://itdost.com/answer-now/Aerobics
http://itdost.com/answer-now/HTML
http://itdost.com/answer-now/CultureI use the following redirect code for each oneRedirect 301 /answer-now/Engineering http://www.itdost.com/questions/
Redirect 301 /answer-now/Food http://www.itdost.com/questions/
Redirect 301 /answer-now/ASP http://www.itdost.com/questions/But as the site structure is big, i wish to do it in a single line instead of writing a line for each redirectSome thing like the following.Redirect 301 /answer-now/% http://www.itdost.com/questions/But the above code does not seems to work | Redirecting all sub-sub pages to another subpage using htaccess |
Check you aren't writing:base_url().'/about'in your queries - base_url() will use the / from your config filealso, remove the second . from this line:RewriteRule ^(.*)$ ./index.php/$1 [L]to read:RewriteRule ^(.*)$ /index.php/$1 [L] | This is my current .htaccess:Options +FollowSymLinks +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L]My config file:$config['base_url'] = 'http://localhost/argh/';
$config['index_page'] = '';And when I click, for example, on the about us link it looks like this:http://localhost/argh//about(2 forward slashes between argh and about)Any suggestion? : )EDIT:Not sure, but this looks like a Codeigniter issue, because the function:function site_url($uri = '')
{
if ($uri == '')
{
return $this->slash_item('base_url').$this->item('index_page');
}
if ($this->item('enable_query_strings') == FALSE)
{
$suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix');
return $this->slash_item('base_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix;
}
else
{
return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri);
}
}More precisely here:return $this->slash_item('base_url').$this->item('index_page');returns the base_url when:$config['index_page'] = '';That's why the previous example ends like this:http://localhost/argh//about | Codeigniter htaccess adds an extra forward slash |
instead of simultaneously tracking the usage as a user clicks on a link, why not make the landing page a PHP script that checks the ip of the user and based on that outputs the links or hides them?
if your files are store in an obvious folder, e.g.
yoursite/music/artist/song.mp3
you can create soft links for them, that way it obfuscates the path.
on linux server you can use symlink() php function to create a soft link to the /music directory and output the path as yoursite/3awE2afeefef4a323/artist/song.mp3 which should still be a direct link to the file, e.g.:<?php
$target = 'music/';
$link = 'a322ewrr323211';
symlink($target, $link);
?>
<html>
<body>
<a href="a322ewrr323211/artist/song.mp3">link</a>
</body>
</html>then periodically delete these symlinks every night or after 24 hours of creation. | I'm being destroyed by robots and malicious users trying to take down my site.I tried making a bandwidth limiter by mod_rewriting all requests for mp3 files to a php script which would track each ip and limit how much each can download per hour. This worked fine but it created alot of problems for some users that the links were not direct links to the mp3 files.I tried all sorts of force download headers but what worked for some users would not work for others.Now, the question is, is it possible to keep direct links to mp3 files and whenever someone clicks on an mp3 file to simultaneously run a tracking php script which would allow or deny the request?thanks!(server does not have mod_bandwidth or any other useful mod) | mp3 bandwidth throttle using htaccess and php |
I'm a little confused about this sentence:www.olddomain.com is have a page will be redirectI'm assuming you mean www.olddomain.com/page redirect to www.exampledomain.com/pagesampleRewriteEngine On
RewriteCond %{HTTP_HOST} .*olddomain\.com$
RewriteCond %{REQUEST_URI} /page/
RewriteRule ^ http://www.exampledomain.com/pagesample [L,R=301]
RewriteCond %{HTTP_HOST} .*olddomain\.com$
RewriteRule ^(.*) http://www.exampledomain.com/page/$1 [L,R=301] | After searching for many post here, I found no luck they are slightly different but I can't handle for now. Please pardon me about this. This are post here I've tried:How to Redirect All urls to a new domain in apache, except one.htaccess rule redirect all pages except a few provided onesHow to 301 redirect all pages from one domain to one single page on a different domainHere is what I want to acquired:all url in www.olddomain.com permanint redirect to www.exampledomain.com/page,and in www.olddomain.com have a page that should be redirect to www.exampledomain.com/pagesamplePlease note: the old olddomain.com have no files except the index and this htaccess, and the www.exampledomain.com is a wordpress site.Thanks in advance | .htaccess redirect all pages except a few pages redirecting with specific page |
Yes, it's called news.php... I renamed the file and exerything is fine now, thanks! Didn't know about this, pretty unobvious bug (or not?)It's not a bug, it sounds like content negotiation (via mod_negotiation) is turned on and it's doing something you don't want. Negotiation can be turned on via a type map or theMultiViewsoption. Typemaps are a little explicit to setup, so I'm assuming since you don't know why this is happening, you haven't set of a specific type that maps tonews.php. So you've probably gotMultiviewsturned on. You can turn it off by either removing it from anOptionsstatement:# remove this word -----------v
Options Indexes FollowSymLinks MultiviewsThis could be anywhere, in your htaccess, server config, vhost config, some config include file, etc. So you can also explicitly unset it in your htaccess file (as long as you aren't also explicitly setting it in the same file):Options -Multiviews | I'm trying to solve this for more than two hours now.
I have a personal site which uses .htaccess to manage urls.
It looks like this:RewriteEngine on
RewriteBase /
...
RewriteRule ^sklad/?$ index.php?action=sklad
RewriteRule ^sklad/user/([0-9]+)?$ index.php?action=sklad&user=$1
RewriteRule ^sklad/folder/(.+)?$ index.php?action=sklad&folder=$1
RewriteRule ^sklad/file/(.+)?$ engine/ajax/sklad.php?file=$1
RewriteRule ^sklad/logout/?$ index.php?action=sklad&op=logout
...
RewriteRule ^admin/?$ admin.php
RewriteRule ^admin/news/?$ admin.php?action=newsthe first five ones work fine. Theadmin/one works fine. But when I try to accessadmin/news/, I get a blank page. No errors displayed or logged by Apache, and no output.admin.php?action=newsis working fine.Bothsklad/andadmin/folders physically exist on the server.BUTwhen I rename the admin/ folder to something elseORchange the the last RewriteRule to something likeRewriteRule ^admin123/news/?$ admin.php?action=newsI can accessadmin123/news/. If it has something to do with the actual folder existing on the server, then why the first five rules are working? This doesn't make sense.I'm out of ideas, hope someone here helps... | .htaccess RewriteRule returns a blank page |
Assuming you want to pass the query string unmodified, you can use the[QSA](query string append) option like so:RewriteRule /(.+)$ /index.php?path=$1 [L,QSA]You can find the documentation for theQSAoptionhere. From the docs:With the [QSA] flag, a request for /pages/123?one=two will be mapped
to /page.php?page=123&one=two. Without the [QSA] flag, that same
request will be mapped to /page.php?page=123 - that is, the existing
query string will be discarded.So, your PHP script will see all the parameters as standard_$_GETparameters, rather than needing to do any other modification.If you would prefer to treat the result more like a typical path element, you can use the following:RewriteRule /(.+)$ /index.php/$1 [L,QSA]In the above case, your query string will still be appended, however you will need to handle the path explicitly using$_SERVER['PATH_INFO']. | I have the following.htaccessRewrite rulebelow which works for converting virtual directories to parameters, for example:www.example.com/usa/ny/nycgets interpreted by PHP aswww.example.com/index.php?path=usa/ny/nyc.What I can't seem to figure out is how I would change myregexbelow to handle parameters of the virtual directories themselves. For example, I want:www.example.com/usa/ny/nyc/?display=off&settings=noneto be seen by PHP aswww.example.com/index.php?path=usa/ny/nyc¶m=display:off,settings:none.What makes it extra tricky is that the parameters won't always be those two options I used in the example above, they will change dynamically. Any ideas or suggestions of how to go about accomplishing this?RewriteRule ^/?([a-zA-Z_\-/]+)$ index.php?path=$1 [L] | Passing $_GET variables to virtual directories via .htaccess |
The media typeapplication/x-httpd-php5was introduced specifically for PHP 5.0,application/x-httpd-php51for PHP 5.1,application/x-httpd-php52for PHP 5.2, etc...In other words: the difference between them is to which version of PHP they are referring.application/x-httpd-phpis kind of obsolete, because it doesn't really refer to any version. This was fine in the early days of PHP, but as the number of versions grew, there was need for something more specific.Most webhosts nowadays support multiple versions of PHP, and their webservers use the media types to pass the correct files to the correct PHP interpreters.If your local development machine has PHP 5.1 or below installed, it's probably the reason why it doesn't support media types for PHP 5.2 and up.A bit off-topic: If you have PHP 5.2 or below installed, I would advise you to upgrade to PHP 5.3 or up. At the time of this writing all versions below 5.3 are deprecated. | What is the difference betweenx-httpd-php5xandapplication/x-httpd-php5xI'v been usingapplication/x-httpd-phpfor years with my web hosting (Linux) until they upgrade PHP to version>=5.2. Now I have to usex-httpd-php5xon web hosting which does not work on localhost (Windows).So everytime I made some changes to the .htaccess, I have to change the AddHandler as well while uploading to web hosting.Is there a cross-platformAddHandlerto parse files as PHP?edit.php can always work, with/without specifing in .htaccess. but not custom extesions, e.g. .myphp | htaccess AddHandler ***x-httpd-php5x*** and ***application/x-httpd-php5x*** |
You ask you new server to act like a proxy for the old server by adding something like this in the new server htaccess :RewriteEngine on
RewriteRule ^forum(/.*)?$ http://your.old.server.ip/forum$1 [L,P] | I'm not sure if this question should be ask here because it is coding related, so if I post in the wrong place please suggest me where should I post.I recently move my server that I use to host in Thailand to Godaddy and I've moved everything except my webboard (forum) and the url it used to be it ishttp://mydomainname.com/forumnow that forum doesn't exist in the new server with godaddy, but it does exist in the directory callforumin the old server. I don't want to make a load to my Godaddy server and thought if I can still host them in the Thai server, but without having to change the old URL.With sub domain I think I know the way how to do it, but I don't know how to do this by poiting to another server but with child directory.I'm not sure if my question is confusing, but what I'm trying to ask is how can I point to another server to to have my forum work on myhttp://mydomainname.com/forum | redirect or point an IP to another server |
The php code you have will insert into the database once that fragment of code is processed.If you execute it more than once, you will see more inserts in the database.However rewrite rules are executed once only, too.So what you experience is likely totally unrelated with your rewrite rules. If you do not trust me, enable logging for the rewrites (see apace docs) and follow the trail.You probably have sit too long in front of the computer, so just get a cup of tea, relax and find that bug. | I have a problem with understanding mod_rewrite behavior.
I'll illustrate this with an example.
I have 3 files in my root directory:.htaccess,index.phpandtest.php.
The content of files:.htaccessRewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.+) ?link=$1 [L]index.php<?php
$db = mysqli_connect('localhost', 'root', '', 'mydb');
$db->real_query ("INSERT INTO `test` (`str`) VALUES ('test_string')");
print_r($_GET);
?>test.php<?php
$db = mysqli_connect('localhost', 'root', '', 'mydb');
$db->real_query ("INSERT INTO `test` (`str`) VALUES ('another_test_string')");
print_r($_GET);
?>So when I go to my site's root folder with the browser,twostrings are inserted in database - 'test_string' and 'test_string'. If I go to/test.php, also two strings will be inserted - one from index.php script - 'test_string' and one fromtest.phpstring - 'another_test_string'. If I remove rewrite rules from .htacess, only one string will be inserted for both pages. I cannot understand such behavior - why all scripts are executed twice? And especially I don't understand why this happens withtest.phpsinceI wrote RewriteCond %{REQUEST_FILENAME} !-f, so no rewrites should be done.Thank you in advance. | Strange behavior in apache mod_rewrite |
Add this to you htaccess :RewriteRule ^(.*)-2(.*)$ /$1$2 [NC,L,R=301] | I have couple of urls which is generated by wordpress/phphttp://mydomain.com/news-2/newsarticlehttp://mydomain.com/products/category-2http://mydomain.com/products/category/products-2how can I rewrite/redirect any url with-2to the one without? The result should behttp://mydomain.com/news/newsarticlehttp://mydomain.com/products/categoryhttp://mydomain.com/products/category/productsThis is what I have so far<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>Thanks | rewrite/redirect specific word from url .htaccess |
You want something like this:# First if someone actually requests a /blog/post.php URL, redirect them
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD)\ /blog/post\.php\?y=([0-9]{4})&m=([0-9]{2})&d=([0-9]{2})&id=([0-9]*)\ HTTP/
RewriteRule ^blog/post\.php$ /blog/%2/%3/%4/%5.php [R=301,L]This will redirect the browser to the/blog/##/##/##/##.phpURI, that will show up in their address bar. Once they get redirected, the browser will then send a request for/blog/##/##/##/##.phpand your server then needs tointernally rewriteitback:# We got pretty URLs, but need to rewrite back to the php request
RewriteRule ^blog/([0-9]{4})/([0-9]{2})/([0-9]{2})/([^\.]+)\.php$ /blog/post.php?y=$1&m=$2&d=$3&id=$4 [L]This changes everything back internally so that the file /blog/post.php can handle the request. | I have a RewriteRule setup to changehttp://kn3rdmeister.com/blog/post.php?y=2012&m=07&d=04&id=4intohttp://kn3rdmeister.com/blog/2012/07/04/4.phpbut that actually redirects where the browser is getting the page from. I want to still display/blog/post.php?y=xxxx&m=xx&d=xx&id=xxbut have the browser show the simpler URL like/blog/post/year/month/day/id.phpI read something somewhere about using ProxyPass, but I don't quite know what I'm doing :PI want people to be able to visit either the post.php URL with the query strings, OR the clean URL with fancy shmancy subdirectories for the dates and get the same content — all while displaying the clean URL in the end. | Using .htaccess to change what URL is being displayed, but without actually redirecting the content? |
Regarding aprevious answer, try:RewriteCond %{SERVER_PORT} !^443$
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R,L] | We have a Symfony 1.4 project and are looking to force HTTPS for all pages in a symfony application using only the htaccess file. I know there are ways to do using filters but I want to know if it's possible to do without that first?Here is the .HTACCESS file I currently am using but isn't working as expected...RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
RewriteCond %{REQUEST_FILENAME} !-fI've also tried without success:RewriteCond %{SERVER_PORT} !^443$
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]I am sure there is some quirk I am missing in doing this with Symfony as this is an easy task to do straight away. Any ideas? | Force HTTPS using only HTACCESS in SYMFONY |
Many browsers send differentAccpet:header in these two situations.When requesting resource from<img src="xxx">:Accept: */*When requesting the url in address bar:Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 | I think the answer to this is no, but ideally I would like to be able to allow image hotlinking, but redirect regular links. For example, if somebody uses this, it should work as expected:<img src='http://mysite.com/image.jpg'/>But if they use this, it would redirect to a different page upon visiting:<a href='http://mysite.com/image.jpg'>Click Here</a>I believe$HTTP_REFERERis the same, regardless of the two methods. Is there any other clever way to distinguish between the two? | Is it possible to tell the difference between hotlinking and regular linking of images using .htaccess? |
It looks like what's happening is the rules in the .htaccess file in the/helpfolder is getting applied because you're requesting something in that folder, so the parent folder's rules won't get applied. You can have your parent rules passed down if you add aRewriteOptions Inheritin your/helpfolder's .htaccess:Options +FollowSymLinks
RewriteOptions Inherit
RewriteRule ^([0-9]+)/?$ index.php?question=$1 [NC,L]
RewriteRule ^category/([^/\.]+)/?$ index.php?category=$1 [NC,L]However, the inherited rules may not be applied in the order that you're expecting. For example, if you requesthttp://www.domain.com/help/1/you'll end up getting redirected tohttp://domain.com/index.php?question=1which may not be what you want if you are trying to make SEO friendly URLs by hiding the query string.Your best bet may be to move the stuff in the/helpfolder into the one in your document root so that you can control the order that the rules will be applied:Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301]
RewriteRule ^help/([0-9]+)/?$ /index.php?question=$1 [NC,L]
RewriteRule ^help/category/([^/\.]+)/?$ /index.php?category=$1 [NC,L]This ensures the redirect to the non-www domainoccurs first, then the/helprules get applied. So when you go tohttp://www.domain.com/help/1/, you first get redirected tohttp://domain.com/help/1/then the help rules get applied and the URI is rewritten to/index.php?question=1. | I am having difficulty getting several mod_rewrite rules to work together in my .htaccess files. Throughout the enitre site I want to drop the "www." from all URLs. I am using the following at the document root:Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301]Then, in one folder "/help" I want to do 2 rewrites:change domain.com/help/1todomain.com/index.php?question=1change domain.com/help/category/exampletodomain.com/index.php?category=exampleSo in domain.com/help I have the following:Options +FollowSymLinks
RewriteRule ^([0-9]+)/?$ index.php?question=$1 [NC,L]
RewriteRule ^category/([^/\.]+)/?$ index.php?category=$1 [NC,L]The above 2 .htaccess files work for:www.domain.comtodomain.comdomain.com/help/1todomain.com/index.php?question=1domain.com/help/category/exampletodomain.com/index.php?category=exampleBut, this does not work when I need to combine the 2 rewrites to both drop the "www." and to rewrite the subfolders to a url variable. e.g.:www.domain.com/help/1todomain.com/index.php?question=1gives a 500 error.Where did I go wrong? And, is this best to do with 2 .htaccess files, or can/should the 2 files be combined into 1 .htaccess file at the document root? | multiple mod_rewrite rules in .htaccess |
I'd guess the typical situations where you'd want to apply rewrite rules to subrequests are more or less the same as the one where you'd use symlinks inside your document root.For a plausible example, let's say you're using Server Side Includes, and have a bunch of files scattered around with suffixes like.html,.shtmland.htm, and perhaps some uppercase variants of these too. At some point, you decide to standardize on the.htmlsuffix, and rename all your files accordingly. But you still have a bunch of legacy code and links that use the other suffixes, and rooting them all out will take a while.In that case, you might want a rewrite rule like this:RewriteRule ^(.*)\.s?html?$ $1.html [NC]By applying this to subrequests too, you ensure that your Server Side Includes don't break because of the renaming. | I found that one of the main things that cause.htaccessrewrite rulesets to do seemingly bizarre things is when Apache decides to try to apply them inside a subrequest. This is to the extent that I now always use the[NS]flag on my rules or use a prefix ruleRewriteCond %{IS_SUBREQ}%{ENV:END} t|1 [NC]
RewriteRule ^ - [L](The %{ENV:END} bit just allows me to use E=END:1 to do the same as the V2.4 END flag.)My Q is:can anyone give me of a good usecase where I wouldn't want to do this?(or alternatively where I would want to use the special-Uor-Fcondition patterns).I realise that there may be many that I haven't thought of, but the A tick goes to the first valid one. | Can anyone think of when a sub-request rewrite is useful? |
I'm sorry but your "URL" transformation are not homogeneous (= it's not possible to "generalize" because they do not shareexactlythe same principles) so here's the best I could do:RewriteEngine On
^/?$ index.php [NC,QSA,L]
^/?about$ about.php [NC,QSA,L]
^/?(agencies|contact|publisher|advertiser)$ /$1.php [NC,QSA,L]
^/?(publisher|agencies|advertiser)/sign_up$ /$1_signup.php [NC,QSA,L]
^/?(publisher|agencies|advertiser)/login$ /login.php [NC,QSA,L]But if you want "homogeneous" stuff that do not perfectly fit with what you're asking, you may have "cleaner" rules like this:RewriteEngine On
^/?$ index.php [NC,QSA,L]
^/?about$ about.php [NC,QSA,L]
^/?(agencies|contact|publisher|advertiser)$ /$1.php [NC,QSA,L]
^/?(agencies|contact|publisher|advertiser)/sign_up$ /$1_signup.php [NC,QSA,L]
^/?(agencies|contact|publisher|advertiser)/login$ /login.php [NC,QSA,L]And if you really want to centralize everything, you could do (= pass the type to thephpfile):RewriteEngine On
^/?$ index.php [NC,QSA,L]
^/?about$ about.php [NC,QSA,L]
^/?(agencies|contact|publisher|advertiser)$ /$1.php [NC,QSA,L]
^/?(agencies|contact|publisher|advertiser)/(sign_up|login)$ /$2.php?type=$1 [NC,QSA,L] | I'm getting ready to develop a web site with the following url structure.I'm a newbie to url rewrites and would like to know the best way to handle this.http://domain.com index.php
http://domain.com/about about.php
http://domain.com/agencies agencies.php
http://domain.com/contact contact.php
http://domain.com/publisher publisher.php
http://domain.com/publisher/sign_up publisher_signup.php
http://domain.com/agencies/sign_up agencies_signup.php
http://domain.com/agencies/login login.php
http://domain.com/advertiser advertiser.php
http://domain.com/advertiser/sign_up advertiser_signup.php
http://domain.com/advertiser/login login.phpWhat would be the most efficient htaccess rewriterule?Should I just manually enter each line with a rewrite or is there some good search/replace I could use?I'm thinking long term the number of slashes in the url could be the most 4
for examplehttp://domain.com/area/sub_area/sub_area2/sub_area3Any help would be greatly appreciated. | URL Rewrite .htaccess |
Found this code as well. Not sure if it will accomplish the same thing. Seems to work for me as does the one above (for PHP).RewriteEngine On
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ /$1 [R=301,L]
# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ /$1 [R=301,L]
# Resolve .php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]I am wondering about the trailing slashes and whether those should be there or omitted? | I have recently changed my website url using htaccess so that my urls will not show file extensions. Now my problem is as I have created a new xml sitemap so that my url will be extensionless!!! the Google webmaster tool is telling me about duplicate content issue!! ie. page and page.html have same title.... so my question is how do i redirect the urls with file extension html to urls with out extension!!!
this is an example of my website url with html extensionhttp://www.shenazhpeyk.co.uk/coding-machines.htmlI want to redirect and change it tohttp://www.shenazhpeyk.co.uk/coding-machinesso that will fix the issue with Google webmaster tools (Please provide me a code for use in htaccess file)Many Thanks | redirecting files with html extension to files without extension (in url) |
Just add the following line to the top of the htaccess in the root. That should prevent it from applying rules beneath it if the url starts with/blog/RewriteRule ^blog/ - [L] | I have a .htaccess with a rewrite-rule which just rewrites all in a parent-folder (/). Now I want to install Wordpress in a child-folder (/blog/), but this doesn't work, because the parent folder rewrites all to another file.Is there any way to exclude the .htaccess of the parent folder from the htacces in /blog/ (which means withoug chaning the .htaccess in /)?I know I could change the .htaccess in /, but this would cause some a lot of other problems... | Overwrite rewrite-rule of htaccess in parent folder |
According to thisforum post, the feature is ready and scheduled forNetBeans 7.2Update:Netbeans 7.2 is out and the feature is finally here. It works with both.htaccessand*.conffiles and looks pretty complete:In any case, syntax highlighting seems to be the only feature so far. There's nothing similar to code intelligence: no navigation, noShow Documentation, no container matching... not even auto-indent! | Is there a way to get Netbeans to color the syntax of .htaccess files?Even differentiating comments from code would be helpful | How to color highlight .htaccess files in Netbeans |
The issue is that Apache httpd is passing it off to Tomcat before Apache looks at the .htaccess. To test this, move your rewrite rules into your vhost. If they work, then that's what the problem was. | I'm working on fixing all my URL's to be shorter with 301 redirects. I have fix almost all of them, however there is a url that is ending with .cfm that will not rewrite.FROM: http://www.mydomain.com/index.cfm/catlink/17/pagelink/7/sublink/34/art/41/rec/1/page.cfm
TO: http://www.mydomain.com/story/resources/health/page/168/page.htmlIf I change/page.cfmto/page.htmlthen the rewrite will work.Here is the rewrite rule that works for my other urlsRewriteRule ^index.cfm/catlink/([a-zA-Z0-9/-]+)([/])pagelink/([a-zA-Z0-9/-]+)([/])sublink/([a-zA-Z0-9/-]+)([/])art/([a-zA-Z0-9/-]+)(.*)$
http://localhost/index.cfm?page=moved&cat=$3&subcat=$5&article=$7&story=$8 [R=301]Why does it work when the URL ends with .html but not when it ends with .cfm? What am I doing wrong?This is current link and will not work:http://www.mydomain.com/index.cfm/catlink/17/pagelink/7/sublink/34/art/41/rec/1/page.cfmIf I manually change the end of it to .html, I can get it to work:http://www.mydomain.com/index.cfm/catlink/17/pagelink/7/sublink/34/art/41/rec/1/page.html | htaccess rewrite rules are not working with urls that end with .cfm |
Itshouldwork both together, however, if you want to provide an endpoint with that header explicitly set, you can do it with PHP as well:header('Access-Control-Allow-Origin: *');Put it into your PHP code before any output starts. Seeheader. | Let me first say that I am running on a shared linux server with HostGator.My problem is I had this line of code in my .htaccess:Header set Access-Control-Allow-Origin *Which allowed cross-domain xhr requests. It was working find till my hosting provider told me to add this to get php 5.3 (which my program requires):# Use PHP 5.3
Action application/x-hg-php53 /cgi-sys/php53
AddHandler application/x-hg-php53 .phpNow I can no longer make cross-domain xhr requests. Does anyone know why this no longer works? (I do get PHP 5.3 though)**Update**Well, it looks like it's something that's not my fault and something I can't fix. Here's the official response from HostGator Tech Support:I've examined your site, the error logs, and the .htaccess directives,
and unfortunately I've come to the conclusion that the "Header set
Access-Control-Allow-Origin *" line is not compatible with our
implementation of PHP 5.3 as found in our shared servers. I sincerely
apologize for the inconvenience that this causes, but the way we
implement and call PHP 5.3 (since 5.2 is the default and cannot be
altered thanks to cPanel) apparently overrides the Header handling
mechanism, making it not work correctly. | .htaccess PHP 5.3 option breaks Access-Control-Allow-Origin option? |
I had this same problem under cPanel. In my case it was due to the "~/.htpasswds/public_html/secure-dir/passwd" file/directory not having the correct permissions. I called the hosting company and they chown'd the file with the correct permissions and it worked.It really had me stumped in that it looked like the directory protection was working b/c it was popping up the AUTH window. But when Apache went to verify the passwd it would choke and serve the WP standard 404 page. | I have a wordpress install with the following htaccess:<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_URI} !^/secure-area/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>and a directory/public_html/secure-area/which has been protected using cPanel.If I turn off prettylinks in Wordpress, I can access the directory normally, but otherwise, I am redirected to the WP 404 page.I can access a directory that is not password protected without any problems.I'm asking here because this is an htaccess problem, not just wordpress specific, and the answers I've seen over here seem better qualified.Many thanks, TimSimilar questions which don't address password protected directories:https://wordpress.stackexchange.com/questions/7181/wordpress-overriding-actual-subdirectorieshttps://wordpress.stackexchange.com/questions/20152/cannot-access-non-wordpress-subdirectories-as-wordpress-overrides-them-with-a-404Can't access my folder because of WordPress | How can I access a password protected directory when htaccess redirects to 404? |
You need to set up your subdomains via theVirtualHostdirective and only add themod_python/mod_wsgihandler in one of theVirtualHosts.You said you loaded the subdomain and it still shows the main site. Would you mind showing us your Apache's site configuration? | I have a Django application hosted on my main domain (example.com), and I now need to host a PHP application on a subdomain (forum.example.com).In the directory of the main domain, I have the following.htaccessentries:SetHandler mod_python
PythonPath "/home/.../apps/example'] + sys.path"
PythonOption mod_python.importer.path "['/home/vlive/python']+ sys.path"
PythonHandler django.core.handlers.modpython
#PythonDebug On
SetEnv DJANGO_SETTINGS_MODULE example.settings
SetEnv PYTHON_EGG_CACHE /tmp/egg-cacheAt present, when I load the subdomain (forum.example.com) I still see the main site (example.com).How can I fix this? | How can I have a Django application on my main domain, and a PHP application on a subdomain? |
Can you put this code in your .htaccess and try again:Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteCond %{HTTP_HOST} ^admin\. [NC]
RewriteRule ^(?!app-admin/) app-admin/webroot%{REQUEST_URI} [L,NC]
RewriteRule ^(?!app/) app/webroot%{REQUEST_URI} [L,NC]Also please report some more details like what URLs are not working. Good place to look at would be apache error.log and access log. | I'm trying to set up a subdomain for my application because I don't want admin code to be mixed into the same folders as regular user code. I'm using CakePHP on a PHPfog server, so I can only use .htaccess to create the subdomain. I have enabled wildcard subdomain support.Here is my folder structure:app
app-admin
cake
plugins
vendors
index.php
.htaccessThe 'app' folder is where the "normal user" site code is located. The "app-admin" folder will be for admins, of course.I'm trying to get a specific rewrite rule that will redirect anything going to the admin.mydomain.com, to the "app-admin" folder. All other subdomains should be ignored (sent to the 'app' folder).The stock .htaccess file in a CakePHP app looks like this:RewriteEngine on
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]Right now I'm trying this with no luck:RewriteEngine on
RewriteCond %{HTTP_HOST} ^admin[NC]
RewriteRule ^$ app-admin/webroot/ [L]
RewriteCond %{HTTP_HOST} ^admin[NC]
RewriteRule (.*) app-admin/webroot/$1 [L]
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]Any help to get this functioning would be greatly appreciated. | .htaccess subdomain redirect to one specific folder - CakePHP App |
Try these rules in your .htaccess file:RewriteEngine on
Options +FollowSymlinks -MultiViews
# to redirect my.site.com to my.site.com/index.html
RewriteRule ^$ /index.html [R,L]
# to redirect /dir1/dir2 to index.php?url=dir1/dir2
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} !^url=
RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?url=$1/$2 [R,L,QSA] | I want to use .htaccess file to return homepage (index.html) if direct access to the web site (no parameters), and index.php/subdirectories/.... if other linksexample :my_site.com displaying index.htmlmy_site.com/dir1/dir2/ must redirect to index.php with parameter dir1/dir2..please help creating this .htaccess filei have in existing file this :RewriteEngine OnRewriteRule ^(.*)(.html|.htm)$ index.php [L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)/?$ index.php [L]i want to do exception to index.html file which serve when entering sitethanks in advance | using .htaccess to serve index.html or index.php |
You have essentially two options:Catch all incoming requests (except for images, style sheets, etc.) into a server-side front controller (PHP, ASP or whatever server-side language you use), and do the redirection there usingheader(....). This is the easiest and most popular way.Use Apache'sRewriteMapdirective to frequently write your maps into text files that mod_rewrite can look up.TheRewriteMapalternative might be beneficial in special omptimization scenarios withlotsof traffic. Usually, chances are you're well off with the first option. | I have a problem with dynamic url rewriting.I have two different kind of url’s that I need to rewrite for SEO purposes. Since these are not fixed, but dynamic – I can’t just setup rules in htaccess as usual. In addition I also have a couple of fixed URL's.All slug names are unique, and are stored in two different tables in my database.Product names (I have a very large list of products)http://www.domain.com/a-big-brown-bear.html(should point to view_product.php)Categories (The categories can be in two levels)http://www.domain.com/cars/ford.htmlhttp://www.domain.com/cars.html(These should point to view_category.php, and both level of menu names should be sent along)What’s the best way of controlling dynamic urls, while still relying on htaccess? Possible someone knows a class to use?PS: My problem is not really writing the rules, but how to fetch the rules from my DB into htaccess.I’m afraid I’m making this more complicated that it really is. All help is appreciated!Thanks in advance,Regards | Dynamic url rewriting htaccess |
There is not only one way, I'm pretty sure. You can create access control with mod_rewrite and[F]on any criteria you would have defined. See for exampleAccess control with mod_rewrite. That said you can perfectly do this.<Location /admin>
[here your rules]
</Location>TheRequiredirective has forcontextdirectory which means that you can use it the context of<Directory>, <Location>, <Files>, and <Proxy>:) | I use the front controller pattern and so all requests are routed through my index.php file. I'd like to secure the 'Admin' controller (accessible at mysite/admin/) with .htpasswd. Only problem is, 'admin' is not a directory but is just a mod_rewrite. Can this be done? | Can I use .htpasswd to secure a nonexistent directory (a virtual mod_rewrite directory)? |
Old thread is old...Stumbled across this while having a similar issue, password protecting a subdomain while keeping the main site without.The solution was easier than I originally made it out to be.In the document_root/.htaccess, domain.com/wiki was redirecting to domain.com/w (because that's cleaner? lol):RewriteEngine On
RewriteRule ^/?w(/.*)?$ /wiki/index.php [PT,L,QSA]
RewriteRule ^/*$ /wiki/index.php [L,QSA]In document_root/wiki/.htaccess the wiki directory was password protected:AuthType Basic
AuthName "Restricted"
AuthUserFile "/home/user/.htpasswds/public_html/wiki/passwd"
require valid-userI simply added this line to the top of document_root/.htaccess so it reads:AuthType None
RewriteEngine On
RewriteRule ^/?w(/.*)?$ /wiki/index.php [PT,L,QSA]
RewriteRule ^/*$ /wiki/index.php [L,QSA]domain.com is no longer password protected and domain.com/wiki redirects as intended and with password protection.Hope it helps someone else. | I have a site with a virtual directory structure likemysite.com/folder/titlewhich is actually a .htaccess rewrite tomysite.com/f/index.php?p=title. I want to password protect the folderfolderwith .htaccess, and know how to do that with actual folders. But I don't want to password protect the main sitemysite.com, and right now if I put the .htaccess file in themysite.comdirectory, I am protectingmysite.comandmysite.com/folder. I have also tried protectingmysite.com/f.How can I protect onlymysite.com/folderusing .htaccess?EDIT: Added .htaccess contents ofmysite.com.<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^folder/(.*)$ /f/index.php?p=$1 [PT,L,QSA]
RewriteRule ^folder/*$ /f/index.php [L,QSA]
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>.htaccess file I tried inmysite.com/fThis successfully protects the entire site when moved tomysite.com, so I know the path is correct. When it is in the subdirectory it generates a 404 error and not a password prompt.AuthName "Restricted Area"
AuthType Basic
AuthUserFile /home/myusername/.htpasswd
require valid-user | Password Protect Virtual Directory With .htaccess |
I would say: no. I think there is now way provided by HTTP. | I have a web application on a site that takes a while (~10 seconds) to complete a portion of the page near the bottom - it has been as optimized as it can be, and caching is not an option.We have compression enabled on the server via an .htaccess directiveSetOutputFilter DEFLATEthe problem is this causes the whole page to be held until completion before it starts outputting to the user, this is not optimal as the user sees nothing until the page completes.I have also tried it via the phpob_start("ob_gzhandler");method.Currently I have a<FilesMatch >in my .htaccess restricting this specific script from being compressed.Basically my question is this - Is there a way to say chunk gzip or deflate so that the user gets it in pieces, so they can see that the page has begun loading? | Any way to chunk gzip with Apache and PHP |
Turn Off ETags [1]FileETag NoneServerTokens Prod, ServerSignature Off [2]ServerTokens prod
ServerSignature Off[1]:http://www.askapache.com/htaccess/apache-speed-etags.htmlTurn off ETags[2]:http://www.petefreitag.com/item/419.cfmServerTokens Prod, ServerSignature Off | I made an .htaccess template; is there anything else that should be added or changed?# DEFAULTS
ServerSignature Off
AddDefaultCharset UTF-8
DefaultLanguage en-US
SetEnv Europe/Belgrade
SetEnv SERVER_ADMIN[email protected]# Rewrites
RewriteEngine On
RewriteBase /
# Redirect to WWW
RewriteCond %{HTTP_HOST} ^serpentineseo.com
RewriteRule (.*) http://www.serpentineseo.com/$1 [R=301,L]
# Cache media files
<filesMatch "\.(gif|jpg|jpeg|png|ico|swf|js)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
<FilesMatch "\.(js|css|pdf|swf)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>
<FilesMatch "\.(html|htm|txt)$">
Header set Cache-Control "max-age=600"
</FilesMatch>
# DONT CACHE
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>
# Deny access to .htaccess
<Files .htaccess>
order allow,deny
deny from all
</Files> | .htaccess template |
A small correction should do the trickRewriteEngine on
RewriteRule ^(.*)/faqs.php$ /faqs/faqs.php?cat=$1 [QSA]"/" is not being passed to parser.Hope it helps | This may seem like a silly question but I can't figure it out.let's say I have a public_html folder with various folders like: Albatross, Blackbirds, Crows and Faqs.I want to make it so that any traffic to Albatross/faqs.php, Blackbirds/faqs.php, Crows/faqs.php etc will see the file that is at faqs/faqs.php?bird=albatross or faqs/faqs.php?bird=crows or what have you.If I go into the Albatross folder's .htaccess file I can do thisRewriteRule faqs.php$ /faqs/faqs.php?cat=albatross[QSA]Which works fine, but I want to put something in the top level .htacces that works for all of them, so tried:RewriteRule faqs.php$ /faqs/faqs.php?cat=albatross[QSA]
RewriteRule /(.*)/faqs.php$ /faqs/faqs.php?cat=$1 [QSA]and evenRewriteRule /albatross/faqs.php$ /faqs/faqs.php?cat=albatross [QSA]and various others but nothing seems to work, when I go tohttp://www.birdsandwhatnot.com/albatross/faqs.phpI see the same file the same way it's always been. Does the presence of an .htaccess file in the subfolder conflict with the higher up .htaccess file?Am I missing something? | Rewrite rules for subfolders |
Rather use the following rewriteruleRewriteRule ^(.*)$ front.php/$1 [L]and access folders by pathinfo infront.php:$pathinfo = $_SERVER['PATH_INFO'];You can alternatively also enableMultiViewsin Apache and configure it to usefront.phpas index file instead and grab pathinfo the same way. | I am cleaning up a large.htaccessfile containing a lot ofmod_rewritestatements.The biggest part of the clutter comes from statements catching various occurrences of/directory1
/directory1/directory2
/directory1/directory2/directory3using statements likeRewriteCond %{REQUEST_URI} ^/([^/]+)/([^/]+)$
RewriteRule .* /front.php?level1=%1&level2=%2&%{QUERY_STRING} [L]
RewriteCond %{REQUEST_URI} ^/([^/]+)/([^/]+)/([^/]+)$
RewriteRule .* /front.php?level1=%1&level2=%2&level3=%3&%{QUERY_STRING} [L]could somebody versed with mod_rewrite give me a pointer on how to write one universal statement that will catch any depth ofdirectory1/directory2...and put the appropriatelevelvariable into the RewriteRule? | Cleaning up nested mod_rewrite statements |
You can tidy this up:You need to put quotes (double or single) around your file nameYou don't need to have "order allow, deny" since you are allowing all 1 line below.Like this is fine:<Files "admin-ajax.php">
Allow from all
Satisfy Any
</Files> | I want to allow only my IP address to access wp-admin but at the same time don't want the calls to admin-ajax.php be blocked. So I want to whitelist admin-ajax.php. Does the following code in .htaccess (placed in wp-admin directory) achieve these objectives:#Protect wp-admin
AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "WordPress Admin Access Control"
AuthType Basic
<LIMIT GET>
order deny,allow
deny from all
allow from <my IP address>
</LIMIT>
#Allow access to wp-admin/admin-ajax.php
<Files admin-ajax.php>
Order allow,deny
Allow from all
Satisfy any
</Files> | Protect wp-admin while whitelisting admin-ajax.php |
The directory was omitted from the rewrite. The character class can also be simplified and the trailing slash can be made optional:RewriteRule ^admin/users/([-\w]+)/?$ admin/users.php?userid=$1A detailed write up of\wcan be found here,http://regular-expressions.info/shorthand.html. In short:\w stands for “word character”. It always matches the ASCII characters [A-Za-z0-9_]regex101 can also be used,http://regex101.com/r/Px2vTE/1 | I'm not the best with .htaccess so I hope someone here can help. I'm trying to rewrite a URL to look more clean.Original URL:domain.com/admin/users?userid=<id>What I want:domain.com/admin/users/<id>I have tried this code but I'm getting a 404:RewriteRule ^admin/users/([a-zA-Z0-9_-]+)$ users.php?userid=$1
RewriteRule ^admin/users/([a-zA-Z0-9_-]+)/$ users.php?userid=$1 | Rewrite URL with htaccess (php) |
Could you please try following, written and tested with your shown samples. Please make sure you clear your browser cache before testing your URLs.RewriteEngine ON
RewriteRule ^live/([^/]*)/([^.]*)\.m3u8/?$ new.php?code=$1&channel=$2 [NC,L] | I need help in making this htaccess rewrite ruleSuppose I have this urlhttp://test.com/new.php?code=6789767897879&channel=1432I need to make ithttp://test.com/live/6789767897879/1432.m3u8where code and channel number are variableSo far I tried this with no luck but it keeps giving me no page found.RewriteEngine On
RewriteBase /
RewriteRule ^/live/(.*)/(.*)?$ /new.php?code=$1&channel=$2I am sorry but I am a beginner. Any effort is appreciated. Thanks again | Writing htaccess rewrite rules |
Your.htaccessfile could be being ignored for multiple reasons, so I would encourage you trying the following steps to determine the cause of your issue:Can Apache read.htaccess?Check file permissions are set to something proper such as0640and make sure its group owner iswww-data.Isrewrite_modenabled?Without it,RewriteEnginewill not work. You can enable rewrites by running2enmod rewritewith root permissions.Have you restarted Apache since the last time you changedhttpd.conf?In case not, restart it by running/etc/init.d/apache2 restart, again with root permissions.If your website is still not working properly after trying these steps, check your Apache error logs. They're usually located in/var/log/apache2/error.log. | I put an .htaccess file in the directory where I am hosting my site. /var/www/html
However it isnt being read.I tried changing the AlowOverride in the httpd config file<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>And my .htaccess works on my local server, however when I try it on my hosted server it doesnt read it at all.Here is my .htaccess file for reference.RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]
RewriteRule ^([0-9]+)$ index.php?week=$1
RewriteRule ^([0-9]+)/$ index.php?week=$1 | .htaccess in /var/www/html directory not being read |
the slash on the end doesnt make much difference. So you just could ignore it, but if you want to allow opening the directories without slash you cant do that in the .htaccess file i think. | I am currently working a project with PHP and Apache on a local server using XAMPP. I have an issue on my website, I was wondering if I can delete the last slash of my web URL. For example, I'm running a website inlocalhostand it was stored in folderhtacces\web\mywebsiteand when I open the website in the browser, the URL bar showslocalhost/web/mywebsite/or127.0.0.1/web/mywebsite/.So if this is normal then it's fine, but why can some site likestackoverflow.comremove the last slashes, also likestackoverflow.com\question\ask?I just want to know about that, is.htaccesswill do? or PHP?
here is the .htacces file that I have written in my websiteRewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [QSA]Could anyone help? | Removing the last slash of URL in XAMPP |
Instead ofHostyou needRefererto access the HTTPRefererheader that is sent in the request. For example:SetEnvIf Referer (.*) custom_referer=$1However, depending on the server-side scripting language you are using, you rarely need to assign this to another variable. You can usually reference it directly as required.Also note, the HTTPRefererheader might not be set. The referring site and the user's browser can both block this.UPDATE:how can i have just the protocol, domain and host without the path.Try changing the regex to something like:SetEnvIf Referer ^(https?://[^/]+) custom_referer=$1If theRefererishttp://example.com:32/welcome, then this should result in justhttp://example.com:32being stored in thecustom_referervariable. | I have the below code, that I can use the below to set a variable:SetEnvIf Host (.*) custom_host=$1What I want is a variable of the requesting host/computer.For example, if the websitehttp://example.com:32/welcomeis making the request, I want this as the variable? | Getting variable of requesting host Apache htaccess? |
Try below code rule, it will work for non existing php files..RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([\w-]+).php/?$ news.php?url=$1 [L] | url is Dynamic
I have urlxyz.com/news.php?url=Facebook-launch-new-messenger-news-16680.phpbut Here i want to remove "news.php?url=" from my above url.I'm coming on this from my index page by clicking on link<a href="news.php?url=<?= $row['url'];?>"><?= $row['title'];?></a>I use this rewrite code in .htaccessRewriteEngine On
RewriteRule ^([a-zA-Z0-9-/]+).php$ news.php?url=$1
RewriteRule ^([a-zA-Z0-9-/]+).php/$ news.php?url=$1help me. | url rewriting remove file name "news.php?url=" from url |
Try the following rule in root/.htaccess:RewriteEngine on
#1 Iteration)Redirect "/pdfs/viewpdf/?id=123" to "/pdfs/123/123.pdf"
RewriteCond %{THE_REQUEST} /pdfs/viewpdf/?\?id=([^&\s]+) [NC]
RewriteRule ^ /pdfs/%1/%1.pdf? [L,R]
#2 iteration) internally map "/pdfs/123/123.pdf" to "/pdfs/viewpdf/?id=123"
RewriteRule ^pdfs/[^/]+/([^.]+)\.pdf$ /pdfs/viewpdf/?id=$1 [L,QSA] | I'm trying to get the following dynamic URL:http://example.com/pdfs/viewpdf?id=1494To be rewritten in the browser's address bar:http://example.com/pdfs/1494/1494.pdfBasically, the user is entering in a request to view a PDF that is available on the file/web server and based on the ID number provided, the URL is rewritten to go and retrieve the document from a sub-folder underDOCUMENT_ROOT/pdfs/whose folder name matches the ID provided along with the PDF filename matching the same ID. What can I try next? Everything I've tried does not work. | Apache mod-rewrite htaccess - dynamic url with parameters |
You can try this rule:RewriteEngine on
RewriteBase /
RewriteRule ^/api/services/notification/send$ /api/services/notification/send.php [L] | This is my first question here and all I can say is that I am really glad to be part of this community.Now, as part of the question. I have a small problem configuring my htaccess properly, I have tried numerous lines of code which I have found here and there, trying my best to come close to something relevant or close to what I want, but no matter what.. I was failing. I tried redirect, redirect 301, both with and without full links, rewrite url with and without extension in the end but nothing happened.So, what's my question exactly.I have a form which when somebody clicks on the "send" button, the form tries to launch a file. It produces the following link:domain.com/api/services/notification/send.php?accept=json&contentType=json&appUrl=http://domain.comAlthough, while I havesend.phpunderapi/services/notification/it's not called at all because there's no extension when the form produces the link, resulting in a 404 error. So, I tried several times to make.htaccessto redirect send intosend.phpbut every time I was facing a huge fail. My assumption is; because it's within other letters/words. Mainly, I want.htaccessto "replace"sendintosend.phpwithout affecting the rest of the URL, usingmod_rewrite.Any insights on this? The last code which I hoped that would work but didn't at all, was this one:Options +FollowSymlinks
RewriteEngine on
RewriteRule ^send?([^/]+) /send.php?accept=json&contentType=json&appUrl=http://domain.com [NC] | How to properly configure .htaccess (rewrite) |
After looking in the right log files see comments in OP, I discovered modsecurity was denying the post request and googling helped me find this solution.Increase the size allowance by adding the following to the site configuration i.e.etc/apache2/sites-available/[your_site.conf]<IfModule mod_security2.c>
SecRequestBodyNoFilesLimit 5242880
</IfModule>I used an arbitrary large number but you can use whatever number you feel comfortable with...you increase exposure/severity of DOS attacks along with the size. | I have 8000 checkboxes in a form being submitted. No comments on how bad that is please.My.htaccessphp_value post_max_size 20M
php_value max_input_vars 10000
php_value suhosin.get.max_vars 10000
php_value suhosin.post.max_vars 10000
php_value suhosin.request.max_vars 10000I am getting theRequest Entity Too Largeerror when I submit the form.When I had 3000 checkboxes it was working fine. Am I missing some more settings or do I need restart a service other than apache?Aside:I checked my post size usingpostsize = $("form").not("[type='file']").serialize().length;The result ispostsize == 165655 | Request Entity Too Large apache |
It depends on your overall directory structure. Take a look atApache .htaccess to hide both .php and .html extentions, for example.If you already have/render/thisconfigured to go to/render.php/this, and all you have to do is perform redirection the other way, then try this:RewriteEngine On
RewriteCond %{REQUEST_URI} \b\.php\b
RewriteRule ^([^/.])\.php/(.*)$ $1/$2 [R](The\bpartmatches at a word boundary, as perpcrepattern(3), which is from thepcrelibrary that bothApachehttpdas well asnginxuse in support of regular expressions.) | I am new to htaccess files, and I understand how to do basic rewrites of URLs such as removing index.php, extensions, etc. I am also able to use $_SERVER["PATH_INFO"] to work with anything trailing the file.What I struggle with is how it would be possible to do this with a trailing faux-directory structure on another file other than the (not-shown) index.php. Lets say I havedomain.com/render.php/thisand I want it to readdomain.com/render/thisMy workaround is currently to do all my logic in my index.php file, but I would like to break it up into several files, so that I would haveindex.phpdoing my home-page stuff, andrender.phpsomething completely different.Thank you for you time. | Treat more than one php file as directory, htaccess |
Change yourwwwrule to make it specific to main domain:RewriteCond %{HTTP_HOST} ^mypage\.com$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L,NE] | I'm trying to redirect my domain's url towwwurl with htaccess.It works fine but problem is that it applies even on subdomain.My subdomain isadminpanel.mypage.combut rewrite engine rewrites even subdomain towww.adminpanel.mypage.com/adminpanel/which is strange and I didn't expect it to work that way. Any possible solution?My code:RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]rewrite engine is on already | Don't apply rewrite engine on subdomain...? |
I would set it to 60 sec, just to be sure that an unforeseen peak load does not causes any problems. | Im looking an enablingkeep-alivevia the.htacessfile. Ive read about enabling thetimeoutparam which would allow me to specify a cut of time for thekeep-alivein specifying this what would a good value be ?The average site load of the home page takes 2.9s (the homepage is almost 14mb of which 98% of that is full screen images, but we lazy load the images so the impact on page load in negligible, the first 2 images and html, css, js are all thats loaded in the first instance hence the 2.9s page load)The rest of the images take up to 30s to download in the background (this is timed with a nonkeep-aliveconnection).Baring that in mind what would an optimaltimeoutbe ? Would setting 30s be ok (is there a downside to going over ?) If we went under does that just mean the client would establish another connection and the site would be loaded in multiplekeep-alivechunks ?For reference to how much load the server can take the site has c. 150-200 visits per day (peak visits per hour are 20-30). The server is a 512gb of ram, VPS with 1tb monthly transfer quota. | Correct timeout value for keep-alive HTTP connections |
You can just tweak regex in your rule and replace 2 rules with this one:RewriteRule ^([a-z]+)(?:\.php)?/?$ default.php?controller=$1 [L,QSA,NC] | I want to use both my old and new url for my site. Recently i have converted to MVC with php. After converting to MVC my old url are not working. But if anyone wants to access the old url, i want he can access the old one. My new urls are likewww.mysite.com/default.php?controller=dashboardI have changed this ugly url by htaccess. Now the display of my new url is likewww.mysite.com/dashboardAnd for this i write the following htaccessRewriteRule ^([a-z]+)$ ./default.php?controller=$1
RewriteRule ^([a-z]+)/$ ./default.php?controller=$1Now problem is that my old url was likewww.mysite.com/dashboard.phpIf anyone tries this type of url with .php ext, this occurs "Error 404". How can both url be accessed likewww.mysite.com/dashboard
www.mysite.com/dashboard.php | Working with both old and new URL using htaccess |
Returns 403 (Forbidden) if you access image directly, but allows them to be displayed on site. It works, but testing can be tricky/misleading. Read about it inquestions/10236717/htaccess-how-to-prevent-a-file-from-direct-url-accessAnother way to prevent hotlinking is like this (from:htaccess generatorsRewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L] | I want to prevent people from getting the images of my website by typing in the URLs in browser address bar, while allowing them to view the images on when visiting the webpages.I tried the following .htaccess code:RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]
RewriteRule \.(gif|jpg|png)$ - [F]However, it not only restricts direct URL access, but also hides all of images even when visiting the webpage. Now my website looks like a page of text with a lot of image holes.Can anyone tell me why the above .htaccess doesn't work?I found it here(htaccess) How to prevent a file from DIRECT URL ACCESS?, but I don't have enough reputation to ask in that post, because I just created this account to post this question.Thanks. | Prevent an image file from DIRECT URL ACCESS? |
To exclude subdomain, you can use a negitive RewriteCondRewriteCond %{HTTP_HOST} !^sub\.domain\.com$
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] | I'm looking to force HTTPS on my entire site except for a subdomain which I am using for a forum. I have an SSL certificate installed on the root domain, but not this forum subdomain. (http://forum.domain.com)Here is the code for forcing HTTPS:RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]However, this also forces HTTPS on subdomains, which effectively makes the forum inaccessible.How can I create an exception rule for this subdomain? | Force HTTPS Through HTACCESS With Subdomain Exception |
One good thing is to you backup MySQL database and open in notepad. Find all links and delete. After that save .sql file and upload back to see.Also look where is inserted javascript/iframe inside your HTML file via source code and find if exist in database and delete.Also reinstall wordpress instalation, reinstall plugins and template (replace all files with new files).That is way how I save many sites.Also can do things what @vard write inyour comment. | One of our Wordpress websites running on an Apache server was recently hacked via PHP injection.The hackers installed hundreds of URLs that redirected to an external eCommerce that sold watches; the URLs were of the formhttp://www.example.com/eta.php?some_file.html; for example:http://www.example.com/eta.php?Jewellery-Watches-Others-c138-4.html.We think we have deleted all infected PHP code. However, the hacked URLs, rather than returning 404, now do a 301 redirect tohttp://www.example.com/?some_file.html(that is, the same URL without theeta.phppart), and finally show the website homepage, returning code 200. Please note that my.htaccessfile seems to be perfectly clean.Where is this phantom redirect coming from?I would be very grateful to anybody that could help me understand what's going on. I am worried that we did not completely wiped out the hack.Thank you for your attention!FURTHER DETAILSThe fileeta.phpis nowhere to be found on the server. Replacingeta.phpwith a random file (ex.ate.php) in the hacked URLs yields a 404 code as expected.In the end I managed to force the hacked URLs to return 404 using the following .htaccess rule:RewriteCond %{THE_REQUEST} /eta\.php
RewriteRule ^(.*)$ - [R=404,L,NC]Interestingly enough, this other rule did not work, as if the hack was somehow messing up with%{REQUEST_URI}:RewriteCond %{REQUEST_URI} ^/eta\.php [NC]
RewriteRule (.*) - [R=404,L] | Hidden redirect in hacked site? |
You can use this.htaccessfile:# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^forest/trees/([^/]+)$ /forest/trees/?type=$1
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPressNow URLs likehttp://example.com/forest/trees/perennialwill internally redirect to/forest/trees/?type=perennialand then to Wordpress Dispatcher/index.php. | I know there are a lot of threads for.htaccessURL rewriting, but my case seems to be a bit different and I have tried a lot but it doesn't work.My current URL:http://example.com/forest/trees/?type=perennialWhat I need is:http://example.com/forest/trees/perennialI just need to remove the?type=from the URL.EDIT: The URL may contain hyphens-between strings at any point (except the domain name ofcourse). It can bedense-forestornon-perennialtoo.It's a custom code and plugin, so can't modify it. I just need the URL beautified.Any help would be greatly appreciated.What I've tried so far in.htaccess:RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD)\ /forest\/trees\/\?type=([^&]+)
RewriteRule ^ \/forest\/trees\/%2\/? [L,R=301]andRewriteRule ^\/forest\/trees\/([^/]*)? /forest/trees/?type=$1 [L]My current Wordpress .htaccess is:# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPressThanks in advance. :)
Cheers! | Wordpress URL - Need to remove a GET parameter |
This will allow you to redirect based on the incoming port, but assumes that apache is listening on all ports (replace {PORT} with the port you want to have redirected):RewriteEngine On
RewriteCond %{SERVER_PORT} ^{PORT}$
RewriteRule ^(.*)$ http://www.redirect.com [L, R=301]Answer partially pulled from.htaccess redirect to error page if port is not 80 | I was wondering how I could redirect a sub domain I own (such as mydomain.dx.am) to another external IP address it is accessed by a specific port.in other words, if you type in this domain, it takes you to the hosted website that is directly attached to the domain (the host is AwardSpace). However, if you access this domain through a specific port (such as 25565 through minecraft), it redirects you to a different external IP (XX.XX.XX.XX). I have tried other services (like NO-IP and free ones), but they don't work forSUBDOMAINSthat you alreadyOWNand for redirection only onSPECIFIC PORTS.I don't want all ports of the subdomain to redirect to a diffferent external IP address, just 1 specific portIs there any online service or specific way of doing this? What could I do to the .htaccess file to create this redirect?I have access to the files of the site/host, and to the .htaccess (directly on the file or automated through the host). I can't seem to find acccess to the DNS Zone file and changing the nameservers is really glitchy and fails most of the time for an unaquired reason...if there is some way to do this with what I have avaliable then please let me know! Thanks!Here is my current .htaccess file (has no problems):# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress | How to redirect a domain to a different IP if accessed by a specific port? |
A better way might be to use what is called the front controller pattern.<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
# Explicitly disable rewriting for front controllers
RewriteRule ^app_dev.php - [L]
RewriteRule ^app.php - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /app.php [QSA,L]
</IfModule>You would get your web server to pass all requests intoapp.phpand then you bootstrap the application and then pass the request on to the relevant scripts.// app.php
//
// Do shared steps like setup the database
switch($_SERVER['REQUEST_URI']) {
case "foo/bar":
require "foo/bar.php";
break;
case "baz/woo":
require "baz/woo.php";
break;
default:
require "404.php";
}The main advantage here is that you are abstracting your URL:s from the actual file structure and also removing the server technology from your URLs which is a good practice. | Hi I have to include a PHP file in all other PHP file of my site.This is a sample of my sitemap:|index.php
|foolder1
|| file1.php
|| check.php
|foolder2
|| file2.php
|foolder3
|| file3.phpI want that all PHP file have includedcheck.php, I must say that I can't editphp.iniand I know there isphp_value auto_prepend_file "check.php"but I don't know how this function run then I'm asking help to usephp_value auto_prepend_fileor another way to include my file in all other PHP file? Thank you in advance.EDIT:I know that in StakOverflow there are some question like this but i can't edit php.ini (some server restrictions...) and I've just try to putphp_value auto_prepend_file "foolder1/check.php"in.htaccessand it run forindex.phpbut not forfile1.php,file2.php,... | How include a PHP file in all other PHP file of a site? |
This is because your relative URIs have their base changed. Originally, the base is/projectwhen the page is/user-list.php, and the browser properly fills in relative links with the/project/base. But when the browser goes to a page like/project/user-list/the base suddenly becomes/project/user-listand it tries to append that in front of all relative URLs and thus none of them load.You can either make your links absolute, or change the URI base in the header of your pages (inbetween the<head> </head>tags):<base href="/project/"> | The problem is that it does not call ajax request when url is rewriten with mod_rewrite.But when I remove the last slash from the link it works.Example link:With this urls it workshttp://localhost/project/user-listhttp://localhost/project/user_list.phpBut when url look like this (added slash to end) ajax request not working.http://localhost/project/user-list/Here is my.htaccess:RewriteEngine On
RewriteRule ^user-list/?$ user_list.php [QSA,L]Calls for .js files look like this:<script src="<?php echo BASE_URL; ?>/js/file.js"></script>BASE_URLdefined with:define('BASE_URL', 'http://localhost/project');I using pluginjquery formcreated bymalsum.Example of form:jQuery:$('#form_example').ajaxForm({
success: function(result) {
alert("success");
}
});HTML:<form id="form_example" action="process.php" method="post">
<input type="text" name="name" placeholder="Enter your name" />
<button type="submit">Submit</button>
</form> | ajax form request not working with mod_rewrite |
Try this in root/.htaccessRewriteEngine on
RewriteCond %{QUERY_STRING} ^.*$
RewriteRule ^/?$ /? [NC,L,R]Empty question mark at the end of target path is importent as it discard the orignal querystrings, in apache 2.4 and later you can useQSDFlag to discard query strings.If the rule above fails, then tryRewriteEngine on
RewriteCond %{THE_REQUEST} /\?([^\s]+) [NC]
RewriteRule ^/?$ /? [NC,L,R] | I need a htaccess rule, if a url contains question mark after main domainfor example:http://example.com/?orhttp://example.com/?xyzit should be redirected to home / index page | I need a htaccess rule, if a url contains question mark after main domain |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.