问:
Rewrite rule doesn't work when I directly type the URL in the browser
I have this directory structure

```<code>/gallery
/home
    index.php
    (other files here).php
/products
/(other folders here)
index.php
</code>```

In the root index.php there is a simple redirect:

```<code><?php header('location: /home/');
</code>```

Indeed, home/index.php is where the site (I mean: HTML, CSS, JS, etc.) starts

Now, since it's a dynamic site, I need some rewrite rules. Here they are, with my comments to help you understand:

```<code># Add a trailing slash to folders that don't have one
# Wehen user types 'mysite.dev/folder' it is converted to 'mysite.dev/folder/'
RewriteCond %{REQUEST_URI} !(/$|\.)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]

# Exclude these folders from rewrite process
# Am I right here? Is this rule right?
RewriteRule ^(admin|ajax|assets|blocks|cache|classes|Connections|cron|editor|inc|intranet|lang|loops|pub)($|/) - [L]

# Remember: the root 'index.php' redirects to '/home' folder: then
# we append the Italian language so that Italian site version is shown as default
RewriteRule ^(/home/)?$ /home/index.php?nLang=it [NC,L]

# Start rewriting rules
RewriteRule ^sfogliabile/([\d]+).htm$                   /flip/browser.php?iCat=$1                              [NC,L]
RewriteRule ^depliant/([\d]+).htm$                      /flip/flyer.php?iSpecial=$1                            [NC,L]
RewriteRule ^([a-z]+)/risultati.htm$                    /home/risultati.php?nLang=$1                           [NC,L,QSA]
RewriteRule ^([a-z]+)/cookie.htm$                       /home/cookie.php?nLang=$1                              [NC,L]
RewriteRule ^([a-z]+)/nojs.htm$                         /home/nojs.php?nLang=$1                                [NC,L]
#RewriteRule ^([a-z]+)/professional/$                   /home/pro.php?nLang=$1                                 [NC,L]
RewriteRule ^([a-z]+)/3/([\w-]+)/$                      /products/index.php?nLang=$1&iModule=3                 [NC,L]       # it/3/prodotti/, en/3/products/
RewriteRule ^([a-z]+)/3/([\w-]+)/([\d]+)/([\w-]+).htm$  /products/details.php?nLang=$1&iData=$3&iModule=3      [NC,L]       # it/3/prodotti/1/prodotto-x.htm, en/3/products/1/product-x.htm
RewriteRule ^([a-z]+)/4/([\w-]+)/$                      /foreground/index.php?nLang=$1&iModule=4               [NC,L]       # it/4/primo-piano/, en/4/foreground/
RewriteRule ^([a-z]+)/4/([\w-]+)/([\d]+)/([\w-]+).htm$  /foreground/details.php?nLang=$1&iData=$3&iModule=4    [NC,L]       # it/4/primo-piano/1/articolo-x.htm, en/4/foreground/1/article-x.htm
RewriteRule ^([a-z]+)/5/([\w-]+)/$                      /specials/index.php?nLang=$1&iModule=5                 [NC,L]       # it/5/speciali/, en/5/specials/
RewriteRule ^([a-z]+)/5/([\w-]+)/([\d]+)/([\w-]+).htm$  /specials/details.php?nLang=$1&iData=$3&iModule=5      [NC,L]       # it/5/speciali/1/articolo-x.htm, en/5/specials/1/article-x.htm
RewriteRule ^([a-z]+)/6/([\w-]+)/$                      /gallery/index.php?nLang=$1&iModule=6                  [NC,L]       # it/6/gallerie/, en/6/galleries/
RewriteRule ^([a-z]+)/6/([\w-]+)/([\d]+)/([\w-]+).htm$  /gallery/details.php?nLang=$1&iData=$3&iModule=6       [NC,L]       # it/6/gallerie/1/galleria-x.htm, en/6/galleries/1/gallery-x.htm
RewriteRule ^([a-z]+)/([\w-]+)/([\d]+)/([\w-]+).htm$    /home/page.php?nLang=$1&iData=$3                       [NC,L,QSA]   # it/azienda/1/pagina-x.htm, en/company/1/page-x.htm

# solution from http://stackoverflow.com/a/39931184/160044
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME}     !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME}     !-f
RewriteRule ^([a-z]+)/$             home/index.php?nLang=$1     [L,QSA,NC]
</code>```

This is fine, seems that everything works as expected, but with an only caveat.
When I type mysite.dev + [Enter] in the browser I am redirected to mysite.dev/home/index.php?nLang=it, exposing things I don't want to and undermining rewrite process: why does it happens? Where am I wrong?

When I delete the /home/index.php?nLang=it part and press [Enter], everything is fine: there is ony the mysite.dev part, that is what I'd expect (or at least mysite.dev/it/ would be fine too)

Want to see the Apache errors.log? Here it is (don't know why it considers also folders that shouldn't be considered, as assets or pub), just replace mysite.dev with ljpharma.dev:

```<code>[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '(.*)' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^(admin|ajax|assets|blocks|cache|classes|Connections|cron|editor|inc|intranet|lang|loops|pub|webassist)($|/)' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^(/home/)?$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^sfogliabile/([\\d]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^depliant/([\\d]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/risultati.htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/cookie.htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/nojs.htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/3/([\\w-]+)/$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/3/([\\w-]+)/([\\d]+)/([\\w-]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/4/([\\w-]+)/$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/4/([\\w-]+)/([\\d]+)/([\\w-]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/5/([\\w-]+)/$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/5/([\\w-]+)/([\\d]+)/([\\w-]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/6/([\\w-]+)/$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/6/([\\w-]+)/([\\d]+)/([\\w-]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/([\\w-]+)/([\\d]+)/([\\w-]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^(.*)$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '(^|/)\\.' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace1] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] pass through D:/Web/ljpharma/home/index.php
</code>```

Any help, please? Thanks

EDIT: Uh-Oh... I noticed that if I put the following rule BEFORE all the other (and NOT AFTER as it's now) everything seems to work... could this be the cause? If yes, am I forced to put this BEFORE everything else or is there a workaround?

```<code>RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
</code>```

答:
You should always place redirects before internal rewrites, even though it is unclear to me why you experience a domain change based on these rules.

When rewriting an url, Apache goes through the .htaccess file repeatedly until the url does no longer change. Why is this important? Well, take the following example:

```<code>#The internal rewrite
RewriteRule ^foo$ /bar [L]

#The external redirect
RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</code>```

When we enter the url http://localhost/foo, Apache will go through the rules and will match the first one. It will now go through the rules again with the url http://localhost/bar and match the second rule and will then redirect to https://localhost/bar. Apache will not evaluate the rules again after encountering the R flag and after the current run through the rules is stopped, e.g. by encountering the L flag or reaching the end of the .htaccess file.

If you put the redirects first, you will match http://localhost/foo against the redirect-rule, which will make the browser request https://localhost/bar. Now Apache will match that url in the new request, which will no longer match any redirects, but will match the internal rewrite, and will internally try to serve resource bar.

On a side-note: In .htaccess files, the matched resource is guaranteed to not start with a / as a .htaccess file is in a directory, and this directory is stripped from the matched url and reapplied after rewriting. As such, the RewriteRule ^(/home/)?$ ... rule is a bit silly, as the part within the parentheses is guaranteed to be never matched. Change it to RewriteRule ^(home/?)?$ ... if you want it to match a path starting with home too.

Body:
I have this directory structure

/gallery
/home
    index.php
    (other files here).php
/products
/(other folders here)
index.php

In the root index.php there is a simple redirect:

<?php header('location: /home/');

Indeed, home/index.php is where the site (I mean: HTML, CSS, JS, etc.) starts

Now, since it's a dynamic site, I need some rewrite rules. Here they are, with my comments to help you understand:

# Add a trailing slash to folders that don't have one
# Wehen user types 'mysite.dev/folder' it is converted to 'mysite.dev/folder/'
RewriteCond %{REQUEST_URI} !(/$|\.)
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]

# Exclude these folders from rewrite process
# Am I right here? Is this rule right?
RewriteRule ^(admin|ajax|assets|blocks|cache|classes|Connections|cron|editor|inc|intranet|lang|loops|pub)($|/) - [L]

# Remember: the root 'index.php' redirects to '/home' folder: then
# we append the Italian language so that Italian site version is shown as default
RewriteRule ^(/home/)?$ /home/index.php?nLang=it [NC,L]

# Start rewriting rules
RewriteRule ^sfogliabile/([\d]+).htm$                   /flip/browser.php?iCat=$1                              [NC,L]
RewriteRule ^depliant/([\d]+).htm$                      /flip/flyer.php?iSpecial=$1                            [NC,L]
RewriteRule ^([a-z]+)/risultati.htm$                    /home/risultati.php?nLang=$1                           [NC,L,QSA]
RewriteRule ^([a-z]+)/cookie.htm$                       /home/cookie.php?nLang=$1                              [NC,L]
RewriteRule ^([a-z]+)/nojs.htm$                         /home/nojs.php?nLang=$1                                [NC,L]
#RewriteRule ^([a-z]+)/professional/$                   /home/pro.php?nLang=$1                                 [NC,L]
RewriteRule ^([a-z]+)/3/([\w-]+)/$                      /products/index.php?nLang=$1&iModule=3                 [NC,L]       # it/3/prodotti/, en/3/products/
RewriteRule ^([a-z]+)/3/([\w-]+)/([\d]+)/([\w-]+).htm$  /products/details.php?nLang=$1&iData=$3&iModule=3      [NC,L]       # it/3/prodotti/1/prodotto-x.htm, en/3/products/1/product-x.htm
RewriteRule ^([a-z]+)/4/([\w-]+)/$                      /foreground/index.php?nLang=$1&iModule=4               [NC,L]       # it/4/primo-piano/, en/4/foreground/
RewriteRule ^([a-z]+)/4/([\w-]+)/([\d]+)/([\w-]+).htm$  /foreground/details.php?nLang=$1&iData=$3&iModule=4    [NC,L]       # it/4/primo-piano/1/articolo-x.htm, en/4/foreground/1/article-x.htm
RewriteRule ^([a-z]+)/5/([\w-]+)/$                      /specials/index.php?nLang=$1&iModule=5                 [NC,L]       # it/5/speciali/, en/5/specials/
RewriteRule ^([a-z]+)/5/([\w-]+)/([\d]+)/([\w-]+).htm$  /specials/details.php?nLang=$1&iData=$3&iModule=5      [NC,L]       # it/5/speciali/1/articolo-x.htm, en/5/specials/1/article-x.htm
RewriteRule ^([a-z]+)/6/([\w-]+)/$                      /gallery/index.php?nLang=$1&iModule=6                  [NC,L]       # it/6/gallerie/, en/6/galleries/
RewriteRule ^([a-z]+)/6/([\w-]+)/([\d]+)/([\w-]+).htm$  /gallery/details.php?nLang=$1&iData=$3&iModule=6       [NC,L]       # it/6/gallerie/1/galleria-x.htm, en/6/galleries/1/gallery-x.htm
RewriteRule ^([a-z]+)/([\w-]+)/([\d]+)/([\w-]+).htm$    /home/page.php?nLang=$1&iData=$3                       [NC,L,QSA]   # it/azienda/1/pagina-x.htm, en/company/1/page-x.htm

# solution from http://stackoverflow.com/a/39931184/160044
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME}     !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME}     !-f
RewriteRule ^([a-z]+)/$             home/index.php?nLang=$1     [L,QSA,NC]

This is fine, seems that everything works as expected, but with an only caveat.
When I type mysite.dev + [Enter] in the browser I am redirected to mysite.dev/home/index.php?nLang=it, exposing things I don't want to and undermining rewrite process: why does it happens? Where am I wrong?

When I delete the /home/index.php?nLang=it part and press [Enter], everything is fine: there is ony the mysite.dev part, that is what I'd expect (or at least mysite.dev/it/ would be fine too)

Want to see the Apache errors.log? Here it is (don't know why it considers also folders that shouldn't be considered, as assets or pub), just replace mysite.dev with ljpharma.dev:

[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '(.*)' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^(admin|ajax|assets|blocks|cache|classes|Connections|cron|editor|inc|intranet|lang|loops|pub|webassist)($|/)' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^(/home/)?$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^sfogliabile/([\\d]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^depliant/([\\d]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.251836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/risultati.htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/cookie.htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/nojs.htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/3/([\\w-]+)/$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/3/([\\w-]+)/([\\d]+)/([\\w-]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/4/([\\w-]+)/$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/4/([\\w-]+)/([\\d]+)/([\\w-]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/5/([\\w-]+)/$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/5/([\\w-]+)/([\\d]+)/([\\w-]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/6/([\\w-]+)/$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/6/([\\w-]+)/([\\d]+)/([\\w-]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/([\\w-]+)/([\\d]+)/([\\w-]+).htm$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^([a-z]+)/$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '^(.*)$' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] strip per-dir prefix: D:/Web/ljpharma/home/index.php -> home/index.php
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace3] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] applying pattern '(^|/)\\.' to uri 'home/index.php'
[Sat Jul 08 16:05:15.252836 2017] [rewrite:trace1] [pid 28420:tid 1232] mod_rewrite.c(477): [client 127.0.0.1:51317] 127.0.0.1 - - [ljpharma.dev/sid#2ee51d8][rid#4ec1ee0/initial] [perdir D:/Web/ljpharma/] pass through D:/Web/ljpharma/home/index.php

Any help, please? Thanks

EDIT: Uh-Oh... I noticed that if I put the following rule BEFORE all the other (and NOT AFTER as it's now) everything seems to work... could this be the cause? If yes, am I forced to put this BEFORE everything else or is there a workaround?

RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Body:
You should always place redirects before internal rewrites, even though it is unclear to me why you experience a domain change based on these rules.

When rewriting an url, Apache goes through the .htaccess file repeatedly until the url does no longer change. Why is this important? Well, take the following example:

#The internal rewrite
RewriteRule ^foo$ /bar [L]

#The external redirect
RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

When we enter the url http://localhost/foo, Apache will go through the rules and will match the first one. It will now go through the rules again with the url http://localhost/bar and match the second rule and will then redirect to https://localhost/bar. Apache will not evaluate the rules again after encountering the R flag and after the current run through the rules is stopped, e.g. by encountering the L flag or reaching the end of the .htaccess file.

If you put the redirects first, you will match http://localhost/foo against the redirect-rule, which will make the browser request https://localhost/bar. Now Apache will match that url in the new request, which will no longer match any redirects, but will match the internal rewrite, and will internally try to serve resource bar.

On a side-note: In .htaccess files, the matched resource is guaranteed to not start with a / as a .htaccess file is in a directory, and this directory is stripped from the matched url and reapplied after rewriting. As such, the RewriteRule ^(/home/)?$ ... rule is a bit silly, as the part within the parentheses is guaranteed to be never matched. Change it to RewriteRule ^(home/?)?$ ... if you want it to match a path starting with home too.


来源: stackexchange

问:
Scrapy spider doesn't want to go to next page
H all,

I am writing a scrapy crawler, here is my previous question about it: Scrapy: AttributeError: 'YourCrawler' object has no attribute 'parse_following_urls'.

Now I am having another problem: it doesnt want to go to the next page:

```<code>from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request

class YourCrawler(CrawlSpider):
    name = "bookstore_2"
    start_urls = [
    'https://example.com/materias/?novedades=LC&p',
    ]
    allowed_domains = ["https://example.com"]

    def parse(self, response):
        # go to the urls in the list
        s = Selector(response)
        page_list_urls = s.xpath('///*[@id="results"]/ul/li/div[1]/h4/a[2]/@href').extract()
        for url in page_list_urls:
            yield Request(response.urljoin(url), callback=self.parse_following_urls, dont_filter=True)

    # For the urls in the list, go inside, and in div#main, take the div.ficha > div.caracteristicas > ul > li
    def parse_following_urls(self, response):
        #Parsing rules go here
        for each_book in response.css('div#main'):
            yield {
            'book_isbn': each_book.css('div.ficha > div.caracteristicas > ul > li').extract(),
            }

        # Return back and go to bext page in div#paginat ul li.next a::attr(href) and begin again
        next_page = response.css('div#paginat ul li.next a::attr(href)').extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)
</code>```

And it works and save the data of the links of the first page, but it fails when trying to go to the next page without any error. This is the log:

```<code>…
2017-07-08 17:17:25 [scrapy.core.scraper] DEBUG: Scraped from <200 https://example.com/book/?id=9780143039617>
{'book_isbn': [u'<li>Editorial: <a href="/search/avanzada/?go=1&editorial=Penguin%20Books">Penguin Books</a></li>', u'<li>P\xe1ginas: 363</li>', u'<li>A\xf1o: 2206</li>', u'<li>Precio: 14.50 \u20ac</li>', u'<li>EAN: 9780143039617</li>']}
2017-07-08 17:17:25 [scrapy.core.engine] INFO: Closing spider (finished)
2017-07-08 17:17:25 [scrapy.extensions.feedexport] INFO: Stored json feed (10 items) in: bookstore_2.json
2017-07-08 17:17:25 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
</code>```

I used this next page section in my first spider, and it was working. Any idea why this happens here?

答:
Your pagination logic should go at the end of parse method instead of parse_following_urls method as the pagination link is on main page and not on book details page. Also, I had to remove the scheme from allowed_domains. Last thing, note that it yields Request at the end of parse method as you don't have scrapy module imported. The spider looks like this:

```<code>from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request

class YourCrawler(CrawlSpider):
    name = "bookstore_2"
    start_urls = [
    'https://lacentral.com/materias/?novedades=LC&p',
    ]
    allowed_domains = ["lacentral.com"]

    def parse(self, response):
        # go to the urls in the list
        s = Selector(response)
        page_list_urls = s.xpath('///[@id="results"]/ul/li/div[1]/h4/a[2]/@href').extract()
        for url in page_list_urls:
            yield Request(response.urljoin(url), callback=self.parse_following_urls, dont_filter=True)

        # Return back and go to bext page in div#paginat ul li.next a::attr(href) and begin again
        next_page = response.css('div#paginat ul li.next a::attr(href)').extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield Request(next_page, callback=self.parse)

    # For the urls in the list, go inside, and in div#main, take the div.ficha > div.caracteristicas > ul > li
    def parse_following_urls(self, response):
        #Parsing rules go here
        for each_book in response.css('div#main'):
            yield {
                'book_isbn': each_book.css('div.ficha > div.caracteristicas > ul > li').extract(),
            }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
H all,

I am writing a scrapy crawler, here is my previous question about it: Scrapy: AttributeError: 'YourCrawler' object has no attribute 'parse_following_urls'.

Now I am having another problem: it doesnt want to go to the next page:

from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request

class YourCrawler(CrawlSpider):
    name = "bookstore_2"
    start_urls = [
    'https://example.com/materias/?novedades=LC&p',
    ]
    allowed_domains = ["https://example.com"]

    def parse(self, response):
        # go to the urls in the list
        s = Selector(response)
        page_list_urls = s.xpath('///*[@id="results"]/ul/li/div[1]/h4/a[2]/@href').extract()
        for url in page_list_urls:
            yield Request(response.urljoin(url), callback=self.parse_following_urls, dont_filter=True)

    # For the urls in the list, go inside, and in div#main, take the div.ficha > div.caracteristicas > ul > li
    def parse_following_urls(self, response):
        #Parsing rules go here
        for each_book in response.css('div#main'):
            yield {
            'book_isbn': each_book.css('div.ficha > div.caracteristicas > ul > li').extract(),
            }

        # Return back and go to bext page in div#paginat ul li.next a::attr(href) and begin again
        next_page = response.css('div#paginat ul li.next a::attr(href)').extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)

And it works and save the data of the links of the first page, but it fails when trying to go to the next page without any error. This is the log:

…
2017-07-08 17:17:25 [scrapy.core.scraper] DEBUG: Scraped from <200 https://example.com/book/?id=9780143039617>
{'book_isbn': [u'
Editorial: Penguin Books
', u'
P\xe1ginas: 363
', u'
A\xf1o: 2206
', u'
Precio: 14.50 \u20ac
', u'
EAN: 9780143039617
']}
2017-07-08 17:17:25 [scrapy.core.engine] INFO: Closing spider (finished)
2017-07-08 17:17:25 [scrapy.extensions.feedexport] INFO: Stored json feed (10 items) in: bookstore_2.json
2017-07-08 17:17:25 [scrapy.statscollectors] INFO: Dumping Scrapy stats:

I used this next page section in my first spider, and it was working. Any idea why this happens here?

Body:
Your pagination logic should go at the end of parse method instead of parse_following_urls method as the pagination link is on main page and not on book details page. Also, I had to remove the scheme from allowed_domains. Last thing, note that it yields Request at the end of parse method as you don't have scrapy module imported. The spider looks like this:

from scrapy.contrib.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request

class YourCrawler(CrawlSpider):
    name = "bookstore_2"
    start_urls = [
    'https://lacentral.com/materias/?novedades=LC&p',
    ]
    allowed_domains = ["lacentral.com"]

    def parse(self, response):
        # go to the urls in the list
        s = Selector(response)
        page_list_urls = s.xpath('///[@id="results"]/ul/li/div[1]/h4/a[2]/@href').extract()
        for url in page_list_urls:
            yield Request(response.urljoin(url), callback=self.parse_following_urls, dont_filter=True)

        # Return back and go to bext page in div#paginat ul li.next a::attr(href) and begin again
        next_page = response.css('div#paginat ul li.next a::attr(href)').extract_first()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield Request(next_page, callback=self.parse)

    # For the urls in the list, go inside, and in div#main, take the div.ficha > div.caracteristicas > ul > li
    def parse_following_urls(self, response):
        #Parsing rules go here
        for each_book in response.css('div#main'):
            yield {
                'book_isbn': each_book.css('div.ficha > div.caracteristicas > ul > li').extract(),
            }


问:
Managing dynamic plotting in matplotlib Animation module
I would like to have an iteratively plotted graph that allows for skipping to the next frame, stopping it and coming back to a previous frame.

I have looked at matplotlib Animation module which would be perfect if there was a way to implement the previous frame functionality (like run Animation backwards for a few frames when a key is pressed)

It would be nice to something like this:

```<code>def update_frame(i, data):
    fig.set_data(data[i])
</code>```

but in a way that I could explicitly manage whether the i iterator increases or decreases.

Is there a way to do that in matplotlib?
Should I look for a different python module?

答:
The FuncAnimation class allows to supply a generator function to the frames argument. This function would be expected to yield a value that is supplied to the updating function for each step of the animantion.

The FuncAnimation doc states:

frames : iterable, int, generator function, or None, optional
  [..]

  If a generator function, then must have the signature

  def gen_function() -> obj:

  In all of these cases, the values in frames is simply passed through to the user-supplied func and thus can be of any type.

We can now create a generator function which yields integers either in forward or in backward direction such that the animation runs forwards  or backwards . To steer the animation, we might use matplotlib.widgets.Buttons and also create a one-step forward  or backward  functionality. This is similar to my answer to the question about looping through a set of images.

The following is a class called Player which subclasses FuncAnimation and incoorporates all of this, allowing to start and stop the animation. It can be instantiated similarly to FuncAnimation,

```<code>ani = Player(fig, update, mini=0, maxi=10)
</code>```

where update would be an updating function, expecting an integer as input, and mini and maxi denote the minimal and maximal number that the function could use. This class stores the value of the current index (self.i), such that if the animation is stopped or reverted it will restart at the current frame.

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import mpl_toolkits.axes_grid1
import matplotlib.widgets

class Player(FuncAnimation):
    def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
                 save_count=None, mini=0, maxi=100, pos=(0.125, 0.92), **kwargs):
        self.i = 0
        self.min=mini
        self.max=maxi
        self.runs = True
        self.forwards = True
        self.fig = fig
        self.func = func
        self.setup(pos)
        FuncAnimation.__init__(self,self.fig, self.func, frames=self.play(),
                                           init_func=init_func, fargs=fargs,
                                           save_count=save_count, **kwargs )

    def play(self):
        while self.runs:
            self.i = self.i+self.forwards-(not self.forwards)
            if self.i > self.min and self.i < self.max:
                yield self.i
            else:
                self.stop()
                yield self.i

    def start(self):
        self.runs=True
        self.event_source.start()

    def stop(self, event=None):
        self.runs = False
        self.event_source.stop()

    def forward(self, event=None):
        self.forwards = True
        self.start()
    def backward(self, event=None):
        self.forwards = False
        self.start()
    def oneforward(self, event=None):
        self.forwards = True
        self.onestep()
    def onebackward(self, event=None):
        self.forwards = False
        self.onestep()

    def onestep(self):
        if self.i > self.min and self.i < self.max:
            self.i = self.i+self.forwards-(not self.forwards)
        elif self.i == self.min and self.forwards:
            self.i+=1
        elif self.i == self.max and not self.forwards:
            self.i-=1
        self.func(self.i)
        self.fig.canvas.draw_idle()

    def setup(self, pos):
        playerax = self.fig.add_axes([pos[0],pos[1], 0.22, 0.04])
        divider = mpl_toolkits.axes_grid1.make_axes_locatable(playerax)
        bax = divider.append_axes("right", size="80%", pad=0.05)
        sax = divider.append_axes("right", size="80%", pad=0.05)
        fax = divider.append_axes("right", size="80%", pad=0.05)
        ofax = divider.append_axes("right", size="100%", pad=0.05)
        self.button_oneback = matplotlib.widgets.Button(playerax, label=ur'$\u29CF$')
        self.button_back = matplotlib.widgets.Button(bax, label=u'$\u25C0$')
        self.button_stop = matplotlib.widgets.Button(sax, label=u'$\u25A0$')
        self.button_forward = matplotlib.widgets.Button(fax, label=u'$\u25B6$')
        self.button_oneforward = matplotlib.widgets.Button(ofax, label=u'$\u29D0$')
        self.button_oneback.on_clicked(self.onebackward)
        self.button_back.on_clicked(self.backward)
        self.button_stop.on_clicked(self.stop)
        self.button_forward.on_clicked(self.forward)
        self.button_oneforward.on_clicked(self.oneforward)

### using this class is as easy as using FuncAnimation:

fig, ax = plt.subplots()
x = np.linspace(0,6*np.pi, num=100)
y = np.sin(x)

ax.plot(x,y)
point, = ax.plot([],[], marker="o", color="crimson", ms=15)

def update(i):
    point.set_data(x[i],y[i])

ani = Player(fig, update, maxi=len(y)-1)

plt.show()
</code>```

Note: This hasn't been written in a way to allow for blitting.

Body:
I would like to have an iteratively plotted graph that allows for skipping to the next frame, stopping it and coming back to a previous frame.

I have looked at matplotlib Animation module which would be perfect if there was a way to implement the previous frame functionality (like run Animation backwards for a few frames when a key is pressed)

It would be nice to something like this:

def update_frame(i, data):
    fig.set_data(data[i])

but in a way that I could explicitly manage whether the i iterator increases or decreases.

Is there a way to do that in matplotlib?
Should I look for a different python module?

Body:
The FuncAnimation class allows to supply a generator function to the frames argument. This function would be expected to yield a value that is supplied to the updating function for each step of the animantion.

The FuncAnimation doc states:

frames : iterable, int, generator function, or None, optional
  [..]

  If a generator function, then must have the signature

  def gen_function() -> obj:

  In all of these cases, the values in frames is simply passed through to the user-supplied func and thus can be of any type.

We can now create a generator function which yields integers either in forward or in backward direction such that the animation runs forwards  or backwards . To steer the animation, we might use matplotlib.widgets.Buttons and also create a one-step forward  or backward  functionality. This is similar to my answer to the question about looping through a set of images.

The following is a class called Player which subclasses FuncAnimation and incoorporates all of this, allowing to start and stop the animation. It can be instantiated similarly to FuncAnimation,

ani = Player(fig, update, mini=0, maxi=10)

where update would be an updating function, expecting an integer as input, and mini and maxi denote the minimal and maximal number that the function could use. This class stores the value of the current index (self.i), such that if the animation is stopped or reverted it will restart at the current frame.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import mpl_toolkits.axes_grid1
import matplotlib.widgets

class Player(FuncAnimation):
    def __init__(self, fig, func, frames=None, init_func=None, fargs=None,
                 save_count=None, mini=0, maxi=100, pos=(0.125, 0.92), **kwargs):
        self.i = 0
        self.min=mini
        self.max=maxi
        self.runs = True
        self.forwards = True
        self.fig = fig
        self.func = func
        self.setup(pos)
        FuncAnimation.__init__(self,self.fig, self.func, frames=self.play(),
                                           init_func=init_func, fargs=fargs,
                                           save_count=save_count, **kwargs )

    def play(self):
        while self.runs:
            self.i = self.i+self.forwards-(not self.forwards)
            if self.i > self.min and self.i < self.max:
                yield self.i
            else:
                self.stop()
                yield self.i

    def start(self):
        self.runs=True
        self.event_source.start()

    def stop(self, event=None):
        self.runs = False
        self.event_source.stop()

    def forward(self, event=None):
        self.forwards = True
        self.start()
    def backward(self, event=None):
        self.forwards = False
        self.start()
    def oneforward(self, event=None):
        self.forwards = True
        self.onestep()
    def onebackward(self, event=None):
        self.forwards = False
        self.onestep()

    def onestep(self):
        if self.i > self.min and self.i < self.max:
            self.i = self.i+self.forwards-(not self.forwards)
        elif self.i == self.min and self.forwards:
            self.i+=1
        elif self.i == self.max and not self.forwards:
            self.i-=1
        self.func(self.i)
        self.fig.canvas.draw_idle()

    def setup(self, pos):
        playerax = self.fig.add_axes([pos[0],pos[1], 0.22, 0.04])
        divider = mpl_toolkits.axes_grid1.make_axes_locatable(playerax)
        bax = divider.append_axes("right", size="80%", pad=0.05)
        sax = divider.append_axes("right", size="80%", pad=0.05)
        fax = divider.append_axes("right", size="80%", pad=0.05)
        ofax = divider.append_axes("right", size="100%", pad=0.05)
        self.button_oneback = matplotlib.widgets.Button(playerax, label=ur'$\u29CF$')
        self.button_back = matplotlib.widgets.Button(bax, label=u'$\u25C0$')
        self.button_stop = matplotlib.widgets.Button(sax, label=u'$\u25A0$')
        self.button_forward = matplotlib.widgets.Button(fax, label=u'$\u25B6$')
        self.button_oneforward = matplotlib.widgets.Button(ofax, label=u'$\u29D0$')
        self.button_oneback.on_clicked(self.onebackward)
        self.button_back.on_clicked(self.backward)
        self.button_stop.on_clicked(self.stop)
        self.button_forward.on_clicked(self.forward)
        self.button_oneforward.on_clicked(self.oneforward)

### using this class is as easy as using FuncAnimation:

fig, ax = plt.subplots()
x = np.linspace(0,6*np.pi, num=100)
y = np.sin(x)

ax.plot(x,y)
point, = ax.plot([],[], marker="o", color="crimson", ms=15)

def update(i):
    point.set_data(x[i],y[i])

ani = Player(fig, update, maxi=len(y)-1)

plt.show()

Note: This hasn't been written in a way to allow for blitting.

ContentLicense: CC BY-SA 4.0


问:
How do I reduce the space below my element/text using padding/margin?
my website learning

Hi everybody.

Im martin.

So im learning to use html and CSS but i'm running through some trouble.
if you are able to see my website (practice) that im trying to create, i wish to reduce the space under the word 'I am ______| learner' and under 'contact'.
I have tried to using padding-bottom but i must be doing something wrong, and i have been playing around for way way too long to understand padding,margins and borders but my head is so confused right now!

Thank you everyone!

```<code>/****************************
CSS
*****************************/

#wrapper {
  margin:15% auto;
  padding:5px;
  max-width:1024px;
}
body {
  color:#988;
  background:white;
  font-family: 'oswald', monospace;
}

/****************************
LOGO/HEADING
****************************/
header {
  background:#a0a0a0;
}

#logo {
  text-decoration:none;

}

h1 {
  font-family:'oswald', monospace;
  font-size:2em;
  color:#fff;
  text-align:center;
  margin:1px;
  padding:7px;
  line-height:0.8em;

}
nav {
  font-size:1em;
  background:#d0d0d0;
  text-align:center;
  padding-top:0px;
  margin-bottom:5px;
  line-height: 1.1em;
  padding-bottom:1px;
}

/****************************
nav a links
*****************************/

nav a, nav a:visited {
  color:#FFF;
}

nav a.selected, nav a:hover {
  color:#131c1f;
}
</code>```

答:
You're seeing the default top and bottom margin on the ul inside of nav. To remove that, just set margin: 0 or change it to whatever value you want.

The top margin is "collapsing" so it shows outside of the parent. You can read more about that here https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

/* normalize */

/*! normalize.css v1.1.0 | MIT License | git.io/normalize */

/* ==========================================================================
   HTML5 display definitions
   ========================================================================== */

/**
 * Correct `block` display not defined in IE 6/7/8/9 and Firefox 3.
 */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
    display: block;
}

/**
 * Correct `inline-block` display not defined in IE 6/7/8/9 and Firefox 3.
 */

audio,
canvas,
video {
    display: inline-block;
    *display: inline;
    *zoom: 1;
}

/**
 * Prevent modern browsers from displaying `audio` without controls.
 * Remove excess height in iOS 5 devices.
 */

audio:not([controls]) {
    display: none;
    height: 0;
}

/**
 * Address styling not present in IE 7/8/9, Firefox 3, and Safari 4.
 * Known issue: no IE 6 support.
 */

[hidden] {
    display: none;
}

/* ==========================================================================
   Base
   ========================================================================== */

/**
 * 1. Correct text resizing oddly in IE 6/7 when body `font-size` is set using
 *    `em` units.
 * 2. Prevent iOS text size adjust after orientation change, without disabling
 *    user zoom.
 */

html {
    font-size: 100%; /* 1 */
    -webkit-text-size-adjust: 100%; /* 2 */
    -ms-text-size-adjust: 100%; /* 2 */
}

/**
 * Address `font-family` inconsistency between `textarea` and other form
 * elements.
 */

html,
button,
input,
select,
textarea {
    font-family: sans-serif;
}

/**
 * Address margins handled incorrectly in IE 6/7.
 */

body {
    margin: 0;
}

/* ==========================================================================
   Links
   ========================================================================== */

/**
 * Address `outline` inconsistency between Chrome and other browsers.
 */

a:focus {
    outline: thin dotted;
}

/**
 * Improve readability when focused and also mouse hovered in all browsers.
 */

a:active,
a:hover {
    outline: 0;
}

/* ==========================================================================
   Typography
   ========================================================================== */

/**
 * Address font sizes and margins set differently in IE 6/7.
 * Address font sizes within `section` and `article` in Firefox 4+, Safari 5,
 * and Chrome.
 */

h1 {
    font-size: 2em;
    margin: 0.67em 0;
}

h2 {
    font-size: 1.5em;
    margin: 0.83em 0;
}

h3 {
    font-size: 1.17em;
    margin: 1em 0;
}

h4 {
    font-size: 1em;
    margin: 1.33em 0;
}

h5 {
    font-size: 0.83em;
    margin: 1.67em 0;
}

h6 {
    font-size: 0.67em;
    margin: 2.33em 0;
}

/**
 * Address styling not present in IE 7/8/9, Safari 5, and Chrome.
 */

abbr[title] {
    border-bottom: 1px dotted;
}

/**
 * Address style set to `bolder` in Firefox 3+, Safari 4/5, and Chrome.
 */

b,
strong {
    font-weight: bold;
}

blockquote {
    margin: 1em 40px;
}

/**
 * Address styling not present in Safari 5 and Chrome.
 */

dfn {
    font-style: italic;
}

/**
 * Address differences between Firefox and other browsers.
 * Known issue: no IE 6/7 normalization.
 */

hr {
    -moz-box-sizing: content-box;
    box-sizing: content-box;
    height: 0;
}

/**
 * Address styling not present in IE 6/7/8/9.
 */

mark {
    background: #ff0;
    color: #000;
}

/**
 * Address margins set differently in IE 6/7.
 */

p,
pre {
    margin: 1em 0;
}

/**
 * Correct font family set oddly in IE 6, Safari 4/5, and Chrome.
 */

code,
kbd,
pre,
samp {
    font-family: monospace, serif;
    _font-family: 'courier new', monospace;
    font-size: 1em;
}

/**
 * Improve readability of pre-formatted text in all browsers.
 */

pre {
    white-space: pre;
    white-space: pre-wrap;
    word-wrap: break-word;
}

/**
 * Address CSS quotes not supported in IE 6/7.
 */

q {
    quotes: none;
}

/**
 * Address `quotes` property not supported in Safari 4.
 */

q:before,
q:after {
    content: '';
    content: none;
}

/**
 * Address inconsistent and variable font size in all browsers.
 */

small {
    font-size: 80%;
}

/**
 * Prevent `sub` and `sup` affecting `line-height` in all browsers.
 */

sub,
sup {
    font-size: 75%;
    line-height: 0;
    position: relative;
    vertical-align: baseline;
}

sup {
    top: -0.5em;
}

sub {
    bottom: -0.25em;
}

/* ==========================================================================
   Lists
   ========================================================================== */

/**
 * Address margins set differently in IE 6/7.
 */

dl,
menu,
ol,
ul {
    margin: 1em 0;
}

dd {
    margin: 0 0 0 40px;
}

/**
 * Address paddings set differently in IE 6/7.
 */

menu,
ol,
ul {
    padding: 0 0 0 40px;
}

/**
 * Correct list images handled incorrectly in IE 7.
 */

nav ul,
nav ol {
    list-style: none;
    list-style-image: none;
    margin: 0;
}

/* ==========================================================================
   Embedded content
   ========================================================================== */

/**
 * 1. Remove border when inside `a` element in IE 6/7/8/9 and Firefox 3.
 * 2. Improve image quality when scaled in IE 7.
 */

img {
    border: 0; /* 1 */
    -ms-interpolation-mode: bicubic; /* 2 */
}

/**
 * Correct overflow displayed oddly in IE 9.
 */

svg:not(:root) {
    overflow: hidden;
}

/* ==========================================================================
   Figures
   ========================================================================== */

/**
 * Address margin not present in IE 6/7/8/9, Safari 5, and Opera 11.
 */

figure {
    margin: 0;
}

/* ==========================================================================
   Forms
   ========================================================================== */

/**
 * Correct margin displayed oddly in IE 6/7.
 */

form {
    margin: 0;
}

/**
 * Define consistent border, margin, and padding.
 */

fieldset {
    border: 1px solid #c0c0c0;
    margin: 0 2px;
    padding: 0.35em 0.625em 0.75em;
}

/**
 * 1. Correct color not being inherited in IE 6/7/8/9.
 * 2. Correct text not wrapping in Firefox 3.
 * 3. Correct alignment displayed oddly in IE 6/7.
 */

legend {
    border: 0; /* 1 */
    padding: 0;
    white-space: normal; /* 2 */
    *margin-left: -7px; /* 3 */
}

/**
 * 1. Correct font size not being inherited in all browsers.
 * 2. Address margins set differently in IE 6/7, Firefox 3+, Safari 5,
 *    and Chrome.
 * 3. Improve appearance and consistency in all browsers.
 */

button,
input,
select,
textarea {
    font-size: 100%; /* 1 */
    margin: 0; /* 2 */
    vertical-align: baseline; /* 3 */
    *vertical-align: middle; /* 3 */
}

/**
 * Address Firefox 3+ setting `line-height` on `input` using `!important` in
 * the UA stylesheet.
 */

button,
input {
    line-height: normal;
}

/**
 * Address inconsistent `text-transform` inheritance for `button` and `select`.
 * All other form control elements do not inherit `text-transform` values.
 * Correct `button` style inheritance in Chrome, Safari 5+, and IE 6+.
 * Correct `select` style inheritance in Firefox 4+ and Opera.
 */

button,
select {
    text-transform: none;
}

/**
 * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
 *    and `video` controls.
 * 2. Correct inability to style clickable `input` types in iOS.
 * 3. Improve usability and consistency of cursor style between image-type
 *    `input` and others.
 * 4. Remove inner spacing in IE 7 without affecting normal text inputs.
 *    Known issue: inner spacing remains in IE 6.
 */

button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
    -webkit-appearance: button; /* 2 */
    cursor: pointer; /* 3 */
    *overflow: visible;  /* 4 */
}

/**
 * Re-set default cursor for disabled elements.
 */

button[disabled],
html input[disabled] {
    cursor: default;
}

/**
 * 1. Address box sizing set to content-box in IE 8/9.
 * 2. Remove excess padding in IE 8/9.
 * 3. Remove excess padding in IE 7.
 *    Known issue: excess padding remains in IE 6.
 */

input[type="checkbox"],
input[type="radio"] {
    box-sizing: border-box; /* 1 */
    padding: 0; /* 2 */
    *height: 13px; /* 3 */
    *width: 13px; /* 3 */
}

/**
 * 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
 * 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
 *    (include `-moz` to future-proof).
 */

input[type="search"] {
    -webkit-appearance: textfield; /* 1 */
    -moz-box-sizing: content-box;
    -webkit-box-sizing: content-box; /* 2 */
    box-sizing: content-box;
}

/**
 * Remove inner padding and search cancel button in Safari 5 and Chrome
 * on OS X.
 */

input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
    -webkit-appearance: none;
}

/**
 * Remove inner padding and border in Firefox 3+.
 */

button::-moz-focus-inner,
input::-moz-focus-inner {
    border: 0;
    padding: 0;
}

/**
 * 1. Remove default vertical scrollbar in IE 6/7/8/9.
 * 2. Improve readability and alignment in all browsers.
 */

textarea {
    overflow: auto; /* 1 */
    vertical-align: top; /* 2 */
}

/* ==========================================================================
   Tables
   ========================================================================== */

/**
 * Remove most spacing between table cells.
 */

table {
    border-collapse: collapse;
    border-spacing: 0;
}

/* main.css */
/****************************
CSS
*****************************/

#wrapper {
  margin:15% auto;
  padding:5px;
  max-width:1024px;
}
body {
  color:#988;
  background:white;
  font-family: 'oswald', monospace;
}

/****************************
LOGO/HEADING
****************************/
header {
  background:#a0a0a0;
}

#logo {
  text-decoration:none;

}

h1 {
  font-family:'oswald', monospace;
  font-size:2em;
  color:#fff;
  text-align:center;
  margin:1px;
  padding:7px;
  line-height:0.8em;

}
nav {
  font-size:1em;
  background:#d0d0d0;
  text-align:center;
  padding-top:0px;
  margin-bottom:5px;
  line-height: 1.1em;
  padding-bottom:1px;
}

/****************************
nav a links
*****************************/

nav a, nav a:visited {
  color:#FFF;
}

nav a.selected, nav a:hover {
  color:#131c1f;
}

nav ul {
margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="http://port-80-3rebi65pw2.treehouse-app.com/css/main.css" rel="stylesheet"/>
<link href="http://port-80-3rebi65pw2.treehouse-app.com/css/normalize.css" rel="stylesheet"/>
<body>
  <header>

      <h1>I AM MARTIN WONG|Learner</h1>

    <nav>
      <ul>
        <li>Portfolio</li>
        <li>About me</li>
        <li>Contact</li>
      </ul>
    </nav>
  </header>

  <div id="wrapper">
  <section>
    <ul>
      <li>

        <img src="img/hongkong1.JPG" alt="">
        <p>Experimentation with monochrome</p>

      </li>
      <li>

        <img src="img/hongkong2.JPG" alt="Tai po">
        <p>Live market</p>

      </li>
        <li>

            <img src="img/singapore1.JPG" alt="Nearby Chinatown">
            <p>Somewhere in Chinatown, Singapore</p>

        </li>
      </ul>
    </section>
  </div>

<footer>© Martin Wong 2017</footer>

</body></code>```

Body:
my website learning

Hi everybody.

Im martin.

So im learning to use html and CSS but i'm running through some trouble.
if you are able to see my website (practice) that im trying to create, i wish to reduce the space under the word 'I am ______| learner' and under 'contact'.
I have tried to using padding-bottom but i must be doing something wrong, and i have been playing around for way way too long to understand padding,margins and borders but my head is so confused right now!

Thank you everyone!

/****************************
CSS
*****************************/

#wrapper {
  margin:15% auto;
  padding:5px;
  max-width:1024px;
}
body {
  color:#988;
  background:white;
  font-family: 'oswald', monospace;
}

/****************************
LOGO/HEADING
****************************/
header {
  background:#a0a0a0;
}

#logo {
  text-decoration:none;

}

h1 {
  font-family:'oswald', monospace;
  font-size:2em;
  color:#fff;
  text-align:center;
  margin:1px;
  padding:7px;
  line-height:0.8em;

}
nav {
  font-size:1em;
  background:#d0d0d0;
  text-align:center;
  padding-top:0px;
  margin-bottom:5px;
  line-height: 1.1em;
  padding-bottom:1px;
}

/****************************
nav a links
*****************************/

nav a, nav a:visited {
  color:#FFF;
}

nav a.selected, nav a:hover {
  color:#131c1f;
}

Body:
You're seeing the default top and bottom margin on the ul inside of nav. To remove that, just set margin: 0 or change it to whatever value you want.

The top margin is "collapsing" so it shows outside of the parent. You can read more about that here https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

/* normalize */

/*! normalize.css v1.1.0 | MIT License | git.io/normalize */

/* ==========================================================================
   HTML5 display definitions
   ========================================================================== */

/**
 * Correct `block` display not defined in IE 6/7/8/9 and Firefox 3.
 */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
    display: block;
}

/**
 * Correct `inline-block` display not defined in IE 6/7/8/9 and Firefox 3.
 */

audio,
canvas,
video {
    display: inline-block;
    *display: inline;
    *zoom: 1;
}

/**
 * Prevent modern browsers from displaying `audio` without controls.
 * Remove excess height in iOS 5 devices.
 */

audio:not([controls]) {
    display: none;
    height: 0;
}

/**
 * Address styling not present in IE 7/8/9, Firefox 3, and Safari 4.
 * Known issue: no IE 6 support.
 */

[hidden] {
    display: none;
}

/* ==========================================================================
   Base
   ========================================================================== */

/**
 * 1. Correct text resizing oddly in IE 6/7 when body `font-size` is set using
 *    `em` units.
 * 2. Prevent iOS text size adjust after orientation change, without disabling
 *    user zoom.
 */

html {
    font-size: 100%; /* 1 */
    -webkit-text-size-adjust: 100%; /* 2 */
    -ms-text-size-adjust: 100%; /* 2 */
}

/**
 * Address `font-family` inconsistency between `textarea` and other form
 * elements.
 */

html,
button,
input,
select,
textarea {
    font-family: sans-serif;
}

/**
 * Address margins handled incorrectly in IE 6/7.
 */

body {
    margin: 0;
}

/* ==========================================================================
   Links
   ========================================================================== */

/**
 * Address `outline` inconsistency between Chrome and other browsers.
 */

a:focus {
    outline: thin dotted;
}

/**
 * Improve readability when focused and also mouse hovered in all browsers.
 */

a:active,
a:hover {
    outline: 0;
}

/* ==========================================================================
   Typography
   ========================================================================== */

/**
 * Address font sizes and margins set differently in IE 6/7.
 * Address font sizes within `section` and `article` in Firefox 4+, Safari 5,
 * and Chrome.
 */

h1 {
    font-size: 2em;
    margin: 0.67em 0;
}

h2 {
    font-size: 1.5em;
    margin: 0.83em 0;
}

h3 {
    font-size: 1.17em;
    margin: 1em 0;
}

h4 {
    font-size: 1em;
    margin: 1.33em 0;
}

h5 {
    font-size: 0.83em;
    margin: 1.67em 0;
}

h6 {
    font-size: 0.67em;
    margin: 2.33em 0;
}

/**
 * Address styling not present in IE 7/8/9, Safari 5, and Chrome.
 */

abbr[title] {
    border-bottom: 1px dotted;
}

/**
 * Address style set to `bolder` in Firefox 3+, Safari 4/5, and Chrome.
 */

b,
strong {
    font-weight: bold;
}

blockquote {
    margin: 1em 40px;
}

/**
 * Address styling not present in Safari 5 and Chrome.
 */

dfn {
    font-style: italic;
}

/**
 * Address differences between Firefox and other browsers.
 * Known issue: no IE 6/7 normalization.
 */

hr {
    -moz-box-sizing: content-box;
    box-sizing: content-box;
    height: 0;
}

/**
 * Address styling not present in IE 6/7/8/9.
 */

mark {
    background: #ff0;
    color: #000;
}

/**
 * Address margins set differently in IE 6/7.
 */

p,
pre {
    margin: 1em 0;
}

/**
 * Correct font family set oddly in IE 6, Safari 4/5, and Chrome.
 */

code,
kbd,
pre,
samp {
    font-family: monospace, serif;
    _font-family: 'courier new', monospace;
    font-size: 1em;
}

/**
 * Improve readability of pre-formatted text in all browsers.
 */

pre {
    white-space: pre;
    white-space: pre-wrap;
    word-wrap: break-word;
}

/**
 * Address CSS quotes not supported in IE 6/7.
 */

q {
    quotes: none;
}

/**
 * Address `quotes` property not supported in Safari 4.
 */

q:before,
q:after {
    content: '';
    content: none;
}

/**
 * Address inconsistent and variable font size in all browsers.
 */

small {
    font-size: 80%;
}

/**
 * Prevent `sub` and `sup` affecting `line-height` in all browsers.
 */

sub,
sup {
    font-size: 75%;
    line-height: 0;
    position: relative;
    vertical-align: baseline;
}

sup {
    top: -0.5em;
}

sub {
    bottom: -0.25em;
}

/* ==========================================================================
   Lists
   ========================================================================== */

/**
 * Address margins set differently in IE 6/7.
 */

dl,
menu,
ol,
ul {
    margin: 1em 0;
}

dd {
    margin: 0 0 0 40px;
}

/**
 * Address paddings set differently in IE 6/7.
 */

menu,
ol,
ul {
    padding: 0 0 0 40px;
}

/**
 * Correct list images handled incorrectly in IE 7.
 */

nav ul,
nav ol {
    list-style: none;
    list-style-image: none;
    margin: 0;
}

/* ==========================================================================
   Embedded content
   ========================================================================== */

/**
 * 1. Remove border when inside `a` element in IE 6/7/8/9 and Firefox 3.
 * 2. Improve image quality when scaled in IE 7.
 */

img {
    border: 0; /* 1 */
    -ms-interpolation-mode: bicubic; /* 2 */
}

/**
 * Correct overflow displayed oddly in IE 9.
 */

svg:not(:root) {
    overflow: hidden;
}

/* ==========================================================================
   Figures
   ========================================================================== */

/**
 * Address margin not present in IE 6/7/8/9, Safari 5, and Opera 11.
 */

figure {
    margin: 0;
}

/* ==========================================================================
   Forms
   ========================================================================== */

/**
 * Correct margin displayed oddly in IE 6/7.
 */

form {
    margin: 0;
}

/**
 * Define consistent border, margin, and padding.
 */

fieldset {
    border: 1px solid #c0c0c0;
    margin: 0 2px;
    padding: 0.35em 0.625em 0.75em;
}

/**
 * 1. Correct color not being inherited in IE 6/7/8/9.
 * 2. Correct text not wrapping in Firefox 3.
 * 3. Correct alignment displayed oddly in IE 6/7.
 */

legend {
    border: 0; /* 1 */
    padding: 0;
    white-space: normal; /* 2 */
    *margin-left: -7px; /* 3 */
}

/**
 * 1. Correct font size not being inherited in all browsers.
 * 2. Address margins set differently in IE 6/7, Firefox 3+, Safari 5,
 *    and Chrome.
 * 3. Improve appearance and consistency in all browsers.
 */

button,
input,
select,
textarea {
    font-size: 100%; /* 1 */
    margin: 0; /* 2 */
    vertical-align: baseline; /* 3 */
    *vertical-align: middle; /* 3 */
}

/**
 * Address Firefox 3+ setting `line-height` on `input` using `!important` in
 * the UA stylesheet.
 */

button,
input {
    line-height: normal;
}

/**
 * Address inconsistent `text-transform` inheritance for `button` and `select`.
 * All other form control elements do not inherit `text-transform` values.
 * Correct `button` style inheritance in Chrome, Safari 5+, and IE 6+.
 * Correct `select` style inheritance in Firefox 4+ and Opera.
 */

button,
select {
    text-transform: none;
}

/**
 * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
 *    and `video` controls.
 * 2. Correct inability to style clickable `input` types in iOS.
 * 3. Improve usability and consistency of cursor style between image-type
 *    `input` and others.
 * 4. Remove inner spacing in IE 7 without affecting normal text inputs.
 *    Known issue: inner spacing remains in IE 6.
 */

button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
    -webkit-appearance: button; /* 2 */
    cursor: pointer; /* 3 */
    *overflow: visible;  /* 4 */
}

/**
 * Re-set default cursor for disabled elements.
 */

button[disabled],
html input[disabled] {
    cursor: default;
}

/**
 * 1. Address box sizing set to content-box in IE 8/9.
 * 2. Remove excess padding in IE 8/9.
 * 3. Remove excess padding in IE 7.
 *    Known issue: excess padding remains in IE 6.
 */

input[type="checkbox"],
input[type="radio"] {
    box-sizing: border-box; /* 1 */
    padding: 0; /* 2 */
    *height: 13px; /* 3 */
    *width: 13px; /* 3 */
}

/**
 * 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
 * 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
 *    (include `-moz` to future-proof).
 */

input[type="search"] {
    -webkit-appearance: textfield; /* 1 */
    -moz-box-sizing: content-box;
    -webkit-box-sizing: content-box; /* 2 */
    box-sizing: content-box;
}

/**
 * Remove inner padding and search cancel button in Safari 5 and Chrome
 * on OS X.
 */

input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
    -webkit-appearance: none;
}

/**
 * Remove inner padding and border in Firefox 3+.
 */

button::-moz-focus-inner,
input::-moz-focus-inner {
    border: 0;
    padding: 0;
}

/**
 * 1. Remove default vertical scrollbar in IE 6/7/8/9.
 * 2. Improve readability and alignment in all browsers.
 */

textarea {
    overflow: auto; /* 1 */
    vertical-align: top; /* 2 */
}

/* ==========================================================================
   Tables
   ========================================================================== */

/**
 * Remove most spacing between table cells.
 */

table {
    border-collapse: collapse;
    border-spacing: 0;
}

/* main.css */
/****************************
CSS
*****************************/

#wrapper {
  margin:15% auto;
  padding:5px;
  max-width:1024px;
}
body {
  color:#988;
  background:white;
  font-family: 'oswald', monospace;
}

/****************************
LOGO/HEADING
****************************/
header {
  background:#a0a0a0;
}

#logo {
  text-decoration:none;

}

h1 {
  font-family:'oswald', monospace;
  font-size:2em;
  color:#fff;
  text-align:center;
  margin:1px;
  padding:7px;
  line-height:0.8em;

}
nav {
  font-size:1em;
  background:#d0d0d0;
  text-align:center;
  padding-top:0px;
  margin-bottom:5px;
  line-height: 1.1em;
  padding-bottom:1px;
}

/****************************
nav a links
*****************************/

nav a, nav a:visited {
  color:#FFF;
}

nav a.selected, nav a:hover {
  color:#131c1f;
}

nav ul {
margin: 0;
}

<link href="http://port-80-3rebi65pw2.treehouse-app.com/css/main.css" rel="stylesheet"/>
<link href="http://port-80-3rebi65pw2.treehouse-app.com/css/normalize.css" rel="stylesheet"/>
<body>
  <header>
    <a href="index.html" id="logo">
      <h1>I AM MARTIN WONG|Learner</h1>
    </a>
    <nav>
      <ul>
        <li><a href="portfolio.html" class="selected">Portfolio</a></li>
        <li><a href="aboutme.html">About me</a></li>
        <li><a href="contact.html">Contact</a></li>
      </ul>
    </nav>
  </header>

  <div id="wrapper">
  <section>
    <ul>
      <li>
        <a href="img/hongkong1.JPG">
        <img src="img/hongkong1.JPG" alt="">
        <p>Experimentation with monochrome</p>
        </a>
      </li>
      <li>
        <a href="img/hongkong2.JPG">
        <img src="img/hongkong2.JPG" alt="Tai po">
        <p>Live market</p>
        </a>
      </li>
        <li>
          <a href="img/singapore1.JPG">
            <img src="img/singapore1.JPG" alt="Nearby Chinatown">
            <p>Somewhere in Chinatown, Singapore</p>
          </a>
        </li>
      </ul>
    </section>
  </div>

<footer>© Martin Wong 2017</footer>

</body>


问:
how to solve error due to chunksize in pandas?
I am trying to read a large csv file and run a code. I use chunk size to do the same.

```<code>file = "./data.csv"
df = pd.read_csv(file, sep="/", header=0,iterator=True, chunksize=1000000, dtype=str)
print len(df.index)
</code>```

I get the following error in the code:

```<code>AttributeError: 'TextFileReader' object has no attribute 'index'
</code>```

How to resolve this?

答:
Those errors are stemming from the fact that your pd.read_csv call, in this case, does not return a DataFrame object. Instead, it returns a TextFileReader object, which is an iterator. This is, essentially, because when you set the iterator parameter to True, what is returned is NOT a DataFrame; it is an iterator of DataFrame objects, each the size of the integer passed to the chunksize parameter (in this case 1000000).
Specific to your case, you can't just call df.index because, simply, an iterator object does not have an index attribute. This does not mean that you cannot access the DataFrames inside the iterator. What it means is that you would either have to loop through the iterator to access one DataFrame at a time or you would have to use some kind of way of concatenating all those DataFrames into one giant one.

If you are considering just working with one DataFrame at a time, then the following is what you would need to do to print the indexes of each DataFrame:

```<code>file = "./data.csv"
dfs = pd.read_csv(file, sep="/", header=0,iterator=True, chunksize=1000000, dtype=str)

for df in dfs:
    print(df.index)
    # do something
    df.to_csv('output_file.csv', mode='a', index=False)
</code>```

This will save the DataFrames into an output file with the name output_file.csv. With the mode parameter set to a, the operations should append to the file. As a result, nothing should be overwritten.

However, if the goal for you is to concatenate all the DataFrames into one giant DataFrame, then the following would perhaps be a better path:

```<code>file = "./data.csv"
dfs = pd.read_csv(file, sep="/", header=0,iterator=True, chunksize=1000000, dtype=str)

giant_df = pd.concat(dfs)

print(giant_df.index)
</code>```

Since you are already using the iterator parameter here, I would assume that you are concerned about memory. As such, the first strategy would be a better one. That basically means that you are taking advantage of the benefits that iterators offer when it comes to memory management for large datasets.

I hope this proves useful.

Body:
I am trying to read a large csv file and run a code. I use chunk size to do the same.

file = "./data.csv"
df = pd.read_csv(file, sep="/", header=0,iterator=True, chunksize=1000000, dtype=str)
print len(df.index)

I get the following error in the code:

AttributeError: 'TextFileReader' object has no attribute 'index'

How to resolve this?

Body:
Those errors are stemming from the fact that your pd.read_csv call, in this case, does not return a DataFrame object. Instead, it returns a TextFileReader object, which is an iterator. This is, essentially, because when you set the iterator parameter to True, what is returned is NOT a DataFrame; it is an iterator of DataFrame objects, each the size of the integer passed to the chunksize parameter (in this case 1000000).
Specific to your case, you can't just call df.index because, simply, an iterator object does not have an index attribute. This does not mean that you cannot access the DataFrames inside the iterator. What it means is that you would either have to loop through the iterator to access one DataFrame at a time or you would have to use some kind of way of concatenating all those DataFrames into one giant one.

If you are considering just working with one DataFrame at a time, then the following is what you would need to do to print the indexes of each DataFrame:

file = "./data.csv"
dfs = pd.read_csv(file, sep="/", header=0,iterator=True, chunksize=1000000, dtype=str)

for df in dfs:
    print(df.index)
    # do something
    df.to_csv('output_file.csv', mode='a', index=False)

This will save the DataFrames into an output file with the name output_file.csv. With the mode parameter set to a, the operations should append to the file. As a result, nothing should be overwritten.

However, if the goal for you is to concatenate all the DataFrames into one giant DataFrame, then the following would perhaps be a better path:

file = "./data.csv"
dfs = pd.read_csv(file, sep="/", header=0,iterator=True, chunksize=1000000, dtype=str)

giant_df = pd.concat(dfs)

print(giant_df.index)

Since you are already using the iterator parameter here, I would assume that you are concerned about memory. As such, the first strategy would be a better one. That basically means that you are taking advantage of the benefits that iterators offer when it comes to memory management for large datasets.

I hope this proves useful.